Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If media queries do not affect specificity, how come the style is being applied even when placed on top

With this style

div {
  @media (min-width: 0px) {
     color: blue;
  }
  color: red;
}
<div>
hello
</div>

I expect the color to be red. However, it’s actually blue and I have no explanation for this. Tested on Chrome. The color is red in other browsers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is because the nested @rule actually unwraps to

@rule {
  & {
    /* ... */
  }
}

This is explained in this paragraph of the specs, which even contains an example pointing out this case:

.foo {
  display: grid;

  @media (orientation: landscape) {
    grid-auto-flow: column;
  }
}
/* equivalent to
  .foo {
    display: grid;

    @media (orientation: landscape) {
      & {
        grid-auto-flow: column;
      }
    }
  }
*/

And if we do add the & selector to the color: red rule, we get the same specificity:

div {
  @media (min-width: 0px) {
     color: blue;
  }
  & { color: red; }
}
<div>
hello
</div>

And note that your code currently produces a red output in non Chromium browsers because they still don’t support CSS nesting, so they just treat the @media rule here as an invalid rule and go on to parse the div one.
If you want to support all browsers, you have to manually unwrap these rules:

@media (min-width: 0px) {
  div { color: blue; }
}
div {
  color: red;
}
<div>
hello<!-- will be red everywhere -->
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading