What are the guidelines for CSS media query overlap?
Cascade.
@media
rules follow the cascade, meaning that when multiple @media
rules match simultaneously, browsers should apply styles from all matching rules and resolve any conflicts through cascading.1
What occurs in all supported browsers at exactly 20em and 45em width?
When the viewport is precisely 20em wide, both your first and second media queries will match. Browsers will apply styles from both @media
rules, resolving conflicts by giving precedence to the last-declared rule. The same applies when the viewport width is exactly 45em for the second and third media queries.
In your provided example code with actual style rules:
@media (max-width: 20em) {
.sidebar { display: none; }
}
@media (min-width: 20em) and (max-width: 45em) {
.sidebar { display: block; float: left; }
}
At exactly 20em wide, both media queries will be true. In this case, display: block
overrides display: none
, and float: left
will be applied to elements with the class .sidebar
.
The cascade operates as if the media query conditions did not exist initially:
.sidebar { display: none; }
.sidebar { display: block; float: left; }
To prevent overlap, ensure that your media queries do not intersect.
Remember, both min-
and max-
prefixes signify "minimum inclusive" and "maximum inclusive," respectively. Thus, (min-width: 20em)
and (max-width: 20em)
will both match a viewport of exactly 20em in width.
Regarding fractional pixel values such as 799.5px, it's unclear how browsers handle them precisely due to logical pixels in CSS. Safari on iOS appears to round fractional values to ensure they fit within defined ranges like max-width: 799px
or min-width: 800px
.
1 While not explicitly stated in the Conditional Rules module or the Cascade module (which is set for revision), the standard implies normal cascading behavior, instructing browsers to apply styles from all matching @media
rules without special hierarchy.