The cascade is what makes CSS special and powerful. But in the case of media queries, overlap can seem problematic.
Consider the following CSS (continuing rules for CSS media query overlap):
/* Standard - for all screens below 20em */
body { color: black; font-size: 1em; }
/* Query A - slightly wider, mobile viewport */
@media (min-width: 20em) and (max-width: 45em) {
body { color: red; } /* supposed to be unique for this width */
}
/* Query B - everything else */
@media (min-width: 45em) {
body { font-size: larger; } /* because viewport is bigger */
}
So when the screen is exactly 45em wide, the overlap at 45em will be treated according to the standard CSS cascade:
- All
max-width: 45em
definitions will be applied first, - and all
min-width: 45em
will be applied thereafter.
Consider these two conditions:
- All text would normally be
black
, but Query A is unique and hascolor: red
. - Since Query B is for larger viewports, it's text has the CSS
font-size: larger
.
Therefore, at a width of exactly 45em, we'd get big and red text. What would be the best solution to avoid this?
I see two possibilities:
Re-declare the text to have
color: black
in Query B, but then you're managing two declarations if you choose to change thecolor
in the future. (Of course, not such a problem with this single line of code, but imagine there's a lot of other declarations and selectors.)Avoid overlap by using pixel values like
max-width: 799px
andmin-width: 800px
, but then you're using pixels — I guess they could be 49.9375em and 50em, respectively. Though what if the default is no longer 16em and something gets rounded? And we're still not certain what happens at that gap. (A black hole that breaks the space-time continuum?)
Both have their drawbacks... any other ideas?
See Question&Answers more detail:os