CSS color property not working correctly on @media

2019-04-28 22:57发布

问题:

I'm building a web app which basically consists of a large form which can then be printed after submission.

However, the text on my print document seems to never be affected by both color and font-weight CSS properties.

Here is a small section of the document as it looks like on screen:

However, when printing, it ends up looking like this:

The font is the same but for some reason no styles are applied to it. I have NO overriding CSS settings for @media print, so shouldn't it just look exactly the same?

Why aren't my normal styles being applied to the print document (by print document I mean the document that appears when you click your browser's Print button)?

EDIT: Posting some example code to illustrate my problem, as requested:

@media print {

    html {
        margin: 0;
        padding: 0;
        width: 100%;
        font-size: 0.9em;
        color: yellow !important;
    }
}

In the above snippet, every attribute will work correctly except color, even when using the !important tag. I am at a loss as to why this is happening.

回答1:

I found the source of the problem: Bootstrap.

I used Chrome's inspector tools to poke around print styles in the Emulation tab, as you can see on the following picture:

I then selected the element whose color was not being applied correctly, which led me to this little gem:

@media print {
    *,
    *:before,
    *:after {
        background: transparent !important;
        color: #000 !important; // Black prints faster: h5bp.com/s
        box-shadow: none !important;
        text-shadow: none !important;
    }

    // Other code...
}

Bootstrap was overriding all my styles with a nasty * !important combo, which will even override an html {color: yellow !important} because of CSS's specificity rules.

To solve my problem I can either delete the above snippet from Bootstrap or make all my own colors !important.



回答2:

I am not seeing any issues appearing when I use your code (slightly modified for ease of obviousness):

html {
  margin: 0;
  padding: 0;
  width: 100%;
  font-size: 100px;
  color: red !important;
}
@media print {
  html {
    color: yellow !important;
  }
}
Red for web, Yellow for print

My print preview in safari displays the text as yellow (ish 0 it looks a little bit greenish but the color most certainly ids not red). I am not sure where you issue will lie, but it's not with this code.