Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force browsers to print background images in CSS?

People also ask

How can I make background image responsive in all devices?

Here's how to create responsive background images with CSS: Use the background-size property to encompass the viewport. Give this property a cover value that will tell a browser to scale the background image's heights and width so that they always remain equal to or greater than the height/width of the device viewport.


With Chrome and Safari you can add the CSS style -webkit-print-color-adjust: exact; to the element to force print the background color and/or image


Browsers, by default, have their option to print background-colors and images turned off. You can add some lines in CSS to bypass this. Just add:

* {
    -webkit-print-color-adjust: exact !important;   /* Chrome, Safari, Edge */
    color-adjust: exact !important;                 /*Firefox*/
}

I found a way to print the background image with CSS. It's a bit dependent on how your background is laid out, but it seems to work for my application.

Essentially, you add the @media print to the end of your stylesheet and change the body background slightly.

Example, if your current CSS looks like this:

body {
background:url(images/mybg.png) no-repeat;
}

At the end of your stylesheet, you add:

@media print {
body {
   content:url(images/mybg.png);
  }
}

This adds the image to the body as a "foreground" image, thus making it printable. You may need to add some additional CSS to make the z-index proper. But again, its up to how your page is laid out.

This worked for me when I couldn't get a header image to show up in print view.


You have very little control over a browser's printing methods. At most you can SUGGEST, but if the browser's print settings have "don't print background images", there's nothing you can do without rewriting your page to turn the background images into floating "foreground" images that happen to be behind other content.


The below code works well for me (at least for Chrome).

I also added some margin and page orientation controls.(portrait, landscape)

<style type="text/css" media="print">
@media print {
  body {-webkit-print-color-adjust: exact;}
}
@page {
    size:A4 landscape;
    margin-left: 0px;
    margin-right: 0px;
    margin-top: 0px;
    margin-bottom: 0px;
    margin: 0;
    -webkit-print-color-adjust: exact;
}
</style>

Make sure to use the !important attribute. This dramatically increases the likelihood your styles are retained when printed.

#example1 {
    background:url(image.png) no-repeat !important;
}

#example2 {
    background-color: #123456 !important;
}