Search code examples
htmlcssmedia-queriescss-specificity

Print media universal (*) rule gets overridden on footer element


I have been searching around trying to find an answer for my question, but simply couldn't find anyone else with my problem, so I decided to turn to stack overflow.

I'm adding CSS rules for @media print and stumbled on a problem that I can't understand. I'm trying to use the * selector to apply background-color: white to all elements, but some elements ignore the rule and continue using the previously defined color, overriding the print media rule.

Here's the simplest CSS file that can reproduce the problem:

footer {
    background-color: lightblue;
}

@media print {
    * {
        background-color: white;
    }
}

And in my HTML I have simple footer tags without any classes or IDs.

...
<footer>
    Footer content here
</footer>
...

I've checked the validity of both, the HTML and the CSS, so it shouldn't be a syntax error

What happens is that if I use Chrome Developer tools option Emulate CSS Media: print or print preview with Background colors and images checked, the footer element retains its light blue color.

If I inspect the element with the Developer tools, it shows the @media print rule has been overridden:

background-color: white;

I can't understand why the footer rule above overrides the * rule. As far as I know, these two rules are of the same specificity, so the one that comes last should be the one applied. But that's not what happens. It works if I edit the rule under the media query to explicitly state that the rule should be applied on footer elements as well:

*, footer {
    background-color: white;
}

But for me that seems really weird, as I thought the * already includes the footer element. I could of course just use the CSS with the footer specified in the rule, but I'd still really want to know why the asterisk alone isn't sufficient.


Solution

  • When you use a media query, it is like an if statement in that if the conditions listed apply, it includes the styles in that block. However, they aren't given a higher specificity just because they're in a media query. The * selector will always have a lower specificity than footer regardless of where it is written.

    This, CSS Tricks, has probably the most comprehensive breakdown of CSS specificity. If you look under "Important Notes" you'll see the specificity of the * is 0,0,0,0 and the footer is 0,0,0,1. You can also check out this, crimsondesigns.com/blog/… (Gotcha #4) that discusses specificity issues with media queries.