The Media Queries Level 4 specification introduced a new range syntax for media queries.
@media (480px <= width < 768px)
This is particularly useful because min-* and max-* media queries have always been inclusive of their boundary values.
A common bug that can be hard to reproduce is when pre-set media queries overlap at the boundaries.
@media (max-width: 768px) {
.example {
padding: 10px;
width: 100%;
}
}
@media (min-width: 768px) {
.example {
// uh oh! Both the margin and the padding will apply
// when the browser is exactly 768px wide 😱
margin: 15px;
width: 200px;
}
}
The classic solution is to make sure that the boundary values differ by 1px.
@media (max-width: 767px) {...}
@media (min-width: 768px) {...}
This works fine for units in px
, but it can be problematic for values using em
.
@media (max-width: 29em) {...}
@media (min-width: 30em) {...} //sizable gap
Since em
units can be modified by the user by way of browser font-size settings, I've typically used 0.001 as my "epsilon" value to make sure that the em
values are less than 1px
apart, while still not causing an overlapping range:
@media (max-width: 29.999em) {...}
@media (min-width: 30em) {...}
Range syntax for media queries simplifies this by allowing both inclusive and exclusive bounds for min-* and max-* boundaries:
@media (width < 30em) {...}
@media (width <= 30em) {...}
Unfortunately, range media queries have almost no browser support at this time.
Fortunately, there's another way to handle exclusive bounds on media queries that does have cross-browser support. This alternative method involves two media query features.
Read More ⇨