Background color not showing in print preview
Asked Answered
P

22

319

I am trying to print a page. In that page I have given a table a background color. When I view the print preview in chrome its not taking on the background color property...

So I tried this property:

-webkit-print-color-adjust: exact; 

but still its not showing the color.

http://jsfiddle.net/TbrtD/

.vendorListHeading {
  background-color: #1a4567;
  color: white;
  -webkit-print-color-adjust: exact; 
}


<div class="bs-docs-example" id="soTable" style="padding-top: 10px;">
  <table class="table" style="margin-bottom: 0px;">
    <thead>
      <tr class="vendorListHeading" style="">
        <th>Date</th>
        <th>PO Number</th>
        <th>Term</th>
        <th>Tax</th>
        <th>Quote Number</th>
        <th>Status</th>
        <th>Account Mgr</th>
        <th>Shipping Method</th>
        <th>Shipping Account</th>
        <th style="width: 184px;">QA</th>
        <th id="referenceSO">Reference</th>
        <th id="referenceSO" style="width: 146px;">End-User Name</th>
        <th id="referenceSO" style="width: 118px;">End-User's PO</th>
        <th id="referenceSO" style="width: 148px;">Tracking Number</th>
      </tr>
    </thead>
    <tbody>
      <tr class="">
        <td>22</td>
        <td>20130000</td>
        <td>Jim B.</td>
        <td>22</td>
        <td>510 xxx yyyy</td>
        <td>[email protected]</td>
        <td>PDF</td>
        <td>12/23/2012</td>
        <td>Approved</td>
        <td>PDF</td>
        <td id="referenceSO">12/23/2012</td>
        <td id="referenceSO">Approved</td>
      </tr>
    </tbody>
  </table>
</div>
Parrie answered 20/2, 2013 at 18:39 Comment(4)
It looks like it works properly: jsfiddle.net/tDggR/2 I'm using chrome version 25Grandam
jsfiddle.net/rajkumart08/TbrtD/1/embedded/result its not working here whyParrie
gosh! It works even in java8 webview engineAgriculturist
Check out my answer https://mcmap.net/q/101031/-css-media-print-issues-with-background-colorDevaughn
T
555

The CSS property print-color-adjust: exact; works appropriately.

However, making sure you have the correct CSS for printing can often be tricky. Several things can be done to avoid the difficulties you are having. First, separate all your print CSS from your screen CSS. This is done via the @media print and @media screen.

Often times just setting up some extra @media print CSS is not enough because you still have all your other CSS included when printing as well. In these cases you just need to be aware of CSS specificity as the print rules don't automatically win against non-print CSS rules.

In your case, the print-color-adjust: exact is working. However, your background-color and color definitions are being beaten out by other CSS with higher specificity.

While I do not endorse using !important in nearly any circumstance, the following definitions work properly and expose the problem:

@media print {
    tr.vendorListHeading {
        background-color: #1a4567 !important;
        print-color-adjust: exact; 
    }
}

@media print {
    .vendorListHeading th {
        color: white !important;
    }
}

Here is the fiddle (and embedded for ease of print previewing).

Temptress answered 6/3, 2013 at 17:8 Comment(4)
When opening the fiddle, I'm getting the Print preview failed. message in Chrome v47.0.2526.106Burnell
Mozilla has marked this as non-standard, so the results are inconsistent and shouldn't be used in production sites developer.mozilla.org/en-US/docs/Web/CSS/…Orthodontics
Yes, this works in Chrome. Bootstrap css was overriding it for me using print media. You can also preview and inspect print mode using the Rendering tab at bottom of Chrome Elements inspector. There's an option for Emulate CSS Media in case you want to see the override stack.Checkbook
Works for me with !important in backgroundGemot
F
118

That CSS property is all you need it works for me...When previewing in Chrome you have the option to see it BW and Color(Color: Options- Color or Black and white) so if you don't have that option, then I suggest to grab this Chrome extension and make your life easier:

https://chrome.google.com/webstore/detail/print-background-colors/gjecpgdgnlanljjdacjdeadjkocnnamk?hl=en

The site you added on fiddle needs this in your media print css (you have it just need to add it...

media print CSS in the body:

@media print {
body {-webkit-print-color-adjust: exact;}
}

UPDATE OK so your issue is bootstrap.css...it has a media print css as well as you do....you remove that and that should give you color....you need to either do your own or stick with bootstraps print css.

When I click print on this I see color.... http://jsfiddle.net/rajkumart08/TbrtD/1/embedded/result/

Foeticide answered 28/2, 2013 at 17:29 Comment(8)
extension works for all the pages but it does not work for my code why jsfiddle.net/rajkumart08/TbrtD/1/embedded/result defie.co/testing/twitter-bootstrap-558bc52/docs/examples/…Parrie
if thats the case make sure your bootstrap has webkit-print-color-adjust: exact; on your body is another way to check...in print media css of courseFoeticide
its not working defie.co/testing/twitter-bootstrap-558bc52/docs/examples/… i gave it in this codeParrie
You did not add it in the print media as I stated in your html inner css: yout html line 1154: @media print { body {margin:0; padding:0; line-height: 1.4em; word-spacing:1px; letter-spacing:0.2px; font: 12px Arial, Helvetica,"Lucida Grande", serif; color: #000;}.... you need to add it in there...Foeticide
I have edited it again but still not working defie.co/testing/twitter-bootstrap-558bc52/docs/examples/…Parrie
jsfiddle.net/rajkumart08/TbrtD/1/embedded/result but i dont see the table heading colors in chromeParrie
you have the color set my friend. The answer is done.... for the other stuff...it requires more print css styling, that is a NEW TOPIC, but you got color and your answer :)Foeticide
in this fiddle i ipdate but i am not getting my table color jsfiddle.net/rajkumart08/TbrtD/3/embedded/result .vendorListHeading { background-color: #1a4567; color: white; -webkit-print-color-adjust: exact; }Parrie
F
64

Chrome will not render background-color, or several other styles, when printing if the background graphics setting is turned off.

This has nothing to do with css, @media, or specificity. You can probably hack your way around it, but the easiest way to get chrome to show the background-color and other graphics is to properly check this checkbox under More Settings.

enter image description here

Frustum answered 27/9, 2017 at 21:28 Comment(1)
Hey, I've finally got around to making a fiddle jsfiddle.net/qm7shrvf for some reason, I cannot get chrome to render the green or red backgrounds in the print preview (I haven't tried to actually print it though) Thanks! (I did observe that the black background of jsfiddle.net does get rendered based on that chrome setting though)Sesquicarbonate
D
38

I just needed to add the !important attribute onto the the background-color tag in order for it to show up, did not need the webkit part:

background-color: #f5f5f5 !important;

Delacruz answered 19/2, 2015 at 16:59 Comment(4)
That's fine..May i know the reason why the color is not shown without giving important @DelacruzCroy
Well don't understand why this is happening but it solved my problem :-)Cidevant
The reason is bootstrap.css, It has a media print css that is taking importance over your css. Following are solutions in this case: - A. override bootstrap media print styles by writing your styles in media print in your css file. - B. give !important to your original styles so that bootstrap media print css cannot override it. In Your case !important have more priority than bootstrap's media print css, That's the reason why !important worked in your case.Lawsuit
It works only when we use style attr example: <td width="35%" style="background-color: #DAEEF3 !important;"> and the webkit is mandatoryArticular
M
15

Your CSS must be like this:

@media print {
   body {
      -webkit-print-color-adjust: exact;
   }
}

.vendorListHeading th {
   background-color: #1a4567 !important;
   color: white !important;   
}
Midyear answered 6/8, 2015 at 22:2 Comment(4)
I have used css in this way but does not work for meDegeneration
This is a non-standard CSS extension that can be used to force printing of background colors and images in browsers based on the WebKit engine, there is an alternative for Firefox, please try using also color-adjust: exact; for more info visit #35625678Midyear
It works only when we use style attr example: <td width="35%" style="background-color: #DAEEF3 !important;">Articular
Miguel you rock!! only person in this thread to mention Firefox, saving my dayOccasional
A
13

TL;DR

The "bug" lost background-color in print preview only appears on table (th, td), but other HTML elements (div,...) or other CSS attributes (border-color,...) still works. Therefore, you can "hack" by wrapping-up anything inside <th> or <td> with a <div> element and set CSS for this <div> (see example below).


Full answer

I tried all suggested solutions here (and in many other questions), such as applied background-color: #000 !important; both in stylesheet and inline, or set

@media print {
  * {
    color-adjust: exact !important;
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
}

, even combined them together, but nothing worked.

After hours of researching without any results, I recognized that the "bug" lost background-color only appears on table (th, td), but other HTML elements (div,...) or other CSS attributes (border-color,...) still works.

Therefore, I came up with a "hack" to wrap-up anything inside <th> or <td> with a <div> (you can adjust padding to make it display same as prior).

In the example below, I used React and makeStyles of @material-ui/core.

JSX:

<Table bordered>
  <thead className={classes.thead}>
    <tr>
      <th><div>Col 1</div></th>
      <th><div>Col 2</div></th>
      <th><div>Col 3</div></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td className={classes.tdGreen}><div>Row 1 - Col 1</div></td>
      <td><div>Row 1 - Col 2</div></td>
      <td><div>Row 1 - Col 3</div></td>
    </tr>
    <tr>
      <td><div>Row 2 - Col 1</div></td>
      <td className={classes.tdBlue}><div>Row 2 - Col 2</div></td>
      <td><div>Row 2 - Col 3</div></td>
    </tr>
  </tbody>
</Table>

Styles:

const useStyles = makeStyles(() => ({
  thead: {
    textAlign: 'center',

    '& th:not(:last-child)': {
      padding: '0',
      '& > div': {
        padding: '.75rem',
        backgroundColor: '#D8D8D8 !important',
      }
    }
  },
  tdGreen: {
    padding: '0 !important',
    '& > div': {
      padding: '.75rem',
      color: 'white',
      backgroundColor: 'green !important',
    }
  },
  tdBlue: {
    padding: '0 !important',
    '& > div': {
      padding: '.75rem',
      color: 'white',
      backgroundColor: 'blue !important',
    }
  }
}));

You can take the idea and convert it into pure HTML/CSS solutions.

Hope this can help anyone struggled with this issue!

Aliped answered 17/1, 2023 at 6:36 Comment(0)
L
12

FOR THOSE USING BOOTSTRAP.CSS, this is the fix!

I have tried all the solutions and they weren't working... until I discovered that bootstrap.css had a super annoying @media print that resets all your colors, background-colors, shadows, etc...

@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}

So either remove this section from bootstrap.css (or bootstrap.min.css)

Or override these values in the css of the page you want to print in your own @media print

@media print {
  body { 
    -webkit-print-color-adjust: exact; 
  }
  .customClass{
     //customCss + !important;
  }
  //more of your custom css
}
Lea answered 15/8, 2018 at 15:18 Comment(0)
B
12

For IE

If you are using IE then go to print preview ( right click on document -> print preview ), go to settings and there is option "print background color and images", select that option and try.

enter image description here

Bodily answered 28/3, 2019 at 9:50 Comment(0)
D
11

if you are using Bootstrap.just use this code in your custom css file. Bootstrap removes all your colors in print preview.

@media print{
  .box-text {

    font-size: 27px !important; 
    color: blue !important;
    -webkit-print-color-adjust: exact !important;
  }
}
Disclamation answered 23/10, 2018 at 4:33 Comment(2)
Adding the important description after my settings helped. I had to have the -webkit-print-color-adjust set at body and then in each of my elements that needed color, I had to declare them important for this to work.Virile
This one is working still now, pretty useful.Edda
C
10

If you are using bootstrap or any other 3rd party CSS, make sure you specify the media screen only on it, so you have the control of the print media type in your own CSS files:

<link rel="stylesheet" media="screen" href="">
Crenshaw answered 16/12, 2015 at 9:51 Comment(1)
Remember, if you add media="screen" to bootstrap css, then every style from bootstrap will be striped out.Haldes
O
5

Are your sure this is a css issue ? There are some posts on google around this issue: http://productforums.google.com/forum/#!category-topic/chrome/discuss-chrome/eMlLBcKqd2s

It may be related to the print process. On safari, which is webkit also, there is a checkbox to print background images and colors in the printer dialog.

Oftentimes answered 6/3, 2013 at 17:9 Comment(0)
W
5

Use the following in your @media print style sheet.

h1 {
    background-color:#404040;
    background-image:url("img/404040.png");
    background-repeat:repeat;
    box-shadow: inset 0 0 0 1000px #404040;
    border:30px solid #404040;
    height:0;
    width:100%;
    color:#FFFFFF !important;
    margin:0 -20px;
    line-height:0px;
}

Here are a couple things to note:

  • background-color is the absolute fallback and is there for posterity mostly.
  • background-image uses a 1px x 1px pixel of #404040 made into a PNG. If the user has images enabled it may work, if not...
  • Set the box-shadow, if that doesn't work...
  • Border = 1/2 your desired height and/or width of box, solid, color. In the example above I wanted a 60px height box.
  • Zero out the heigh/width depending on what you're controlling in the border attribute.
  • Font color will default to black unless you use !important
  • Set line-height to 0 to fix for the box not having physical dimension.
  • Make and host your own PNGs :-)
  • If the text in the block needs to wrap, put it in a div and position the div using position:relative; and remove line-height.

See my fiddle for a more detailed demonstration.

Waistline answered 24/5, 2013 at 16:8 Comment(0)
B
1

There's a style in the bootstrap css files under @media print{*,:after,:before ....} that has color and background styles labeled !important, which remove any background colors on any elements. Kill those two pieces of css and it will work.

Bootstrap is making the executing decision that you should never have any background color in prints, so you have to edit their css or have another !important style that is a higher precedence. Good job bootstrap...

Barde answered 31/5, 2016 at 15:38 Comment(0)
V
1

I used purgatory101's answer but had trouble keeping all colours (icons, backgrounds, text colours etc...), especially that CSS stylesheets cannot be used with libraries which dynamically change DOM element's colours. Therefore here is a script that changes element's styles (background-colour and colour) before printing and clears styles once printing is done. It is useful to avoid writing a lot of CSS in a @media print stylesheet as it works whatever the page structure.

There is a part of the script that is specially made to keep FontAwesome icons color (or any element that uses a :before selector to insert coloured content).

JSFiddle showing the script in action

Compatibility: works in Chrome, I did not test other browsers.

function setColors(selector) {
  var elements = $(selector);
  for (var i = 0; i < elements.length; i++) {
    var eltBackground = $(elements[i]).css('background-color');
    var eltColor = $(elements[i]).css('color');

    var elementStyle = elements[i].style;
    if (eltBackground) {
      elementStyle.oldBackgroundColor = {
        value: elementStyle.backgroundColor,
        importance: elementStyle.getPropertyPriority('background-color'),
      };
      elementStyle.setProperty('background-color', eltBackground, 'important');
    }
    if (eltColor) {
      elementStyle.oldColor = {
        value: elementStyle.color,
        importance: elementStyle.getPropertyPriority('color'),
      };
      elementStyle.setProperty('color', eltColor, 'important');
    }
  }
}

function resetColors(selector) {
  var elements = $(selector);
  for (var i = 0; i < elements.length; i++) {
    var elementStyle = elements[i].style;

    if (elementStyle.oldBackgroundColor) {
      elementStyle.setProperty('background-color', elementStyle.oldBackgroundColor.value, elementStyle.oldBackgroundColor.importance);
      delete elementStyle.oldBackgroundColor;
    } else {
      elementStyle.setProperty('background-color', '', '');
    }
    if (elementStyle.oldColor) {
      elementStyle.setProperty('color', elementStyle.oldColor.value, elementStyle.oldColor.importance);
      delete elementStyle.oldColor;
    } else {
      elementStyle.setProperty('color', '', '');
    }
  }
}

function setIconColors(icons) {
  var css = '';
  $(icons).each(function (k, elt) {
    var selector = $(elt)
      .parents()
      .map(function () { return this.tagName; })
      .get()
      .reverse()
      .concat([this.nodeName])
      .join('>');

    var id = $(elt).attr('id');
    if (id) {
      selector += '#' + id;
    }

    var classNames = $(elt).attr('class');
    if (classNames) {
      selector += '.' + $.trim(classNames).replace(/\s/gi, '.');
    }

    css += selector + ':before { color: ' + $(elt).css('color') + ' !important; }';
  });
  $('head').append('<style id="print-icons-style">' + css + '</style>');
}

function resetIconColors() {
  $('#print-icons-style').remove();
}

And then modify the window.print function to make it set the styles before printing and resetting them after.

window._originalPrint = window.print;
window.print = function() {
  setColors('body *');
  setIconColors('body .fa');
  window._originalPrint();
  setTimeout(function () {
    resetColors('body *');
    resetIconColors();
  }, 100);
}

The part that finds icons paths to create CSS for :before elements is a copy from this SO answer

Veer answered 10/8, 2017 at 17:16 Comment(1)
It works, thanks (note that you will need to remove var from window on your last code snippet)Dizzy
J
1

If you are using nextjs or react add this to the global css:

  @media print {
   body {
      -webkit-print-color-adjust: exact;
   }
}

This worked for me.

Jessie answered 29/11, 2022 at 3:12 Comment(0)
C
0

You can also use the box-shadow property.

Chitter answered 22/11, 2017 at 7:41 Comment(0)
R
0

The best solution for this if you are using bootstrap so just do one thing remove @media print {} all code inside this. and enable background graphics from more settings while taking print preview.

Ronironica answered 25/1, 2019 at 10:47 Comment(2)
Why remove all print CSS while printing?Crissycrist
This is to make color visible for printRonironica
T
0

You can use inline css styles with !important. Eg.

<p style="background:red!important">ABCD</p>
Tommyetommyrot answered 9/4, 2021 at 5:59 Comment(0)
F
0

you can download bootstrap 4 css from bootstrap web and looking on the bottom code look where code is

and remove this css style because this override your css color table style

First answered 13/12, 2022 at 17:15 Comment(0)
A
0

Try

background: linear-gradient(#1a4567 , #1a4567)

This worked for me.

Avalon answered 10/6, 2023 at 12:23 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Eldest
M
-1

If you download Bootstrap without the "Print media styles" option, you will not have this problem and do not have to remove the "@media print" code manually in your bootstrap.css file.

Misrepresent answered 17/6, 2016 at 19:54 Comment(0)
R
-1

I double load my external css source file and change the media="screen" to media="print" and all the borders for my table were shown

Try this :

<link rel="stylesheet" media="print" href="bootstrap.css" />

<link rel="stylesheet" media="screen" href="bootstrap.css" />
Rosenthal answered 19/12, 2016 at 12:51 Comment(1)
this could be done with media="all" instead of two link tagsFranklin

© 2022 - 2024 — McMap. All rights reserved.