min-width vs max-width media queries in CSS
32 min-width, max-width, and the overlap at the boundary
fairWork out which of two queries applies at a given width, and find the width where both of them match at once.
Stuck? Three hints, smallest first
- 1.
min-widthmeans “this wide or wider”.max-widthmeans “this wide or narrower”. Both are inclusive. - 2. So
max-width: 40emandmin-width: 40emboth match at exactly 40em. - 3. Pick one direction per stylesheet, or subtract a hair from the max-width bound.
<p class="banner">Resize the preview: the label below changes at 40em.</p>
<p class="wide-only">Wide layout is active.</p>
<p class="narrow-only">Narrow layout is active.</p>
.banner, .wide-only, .narrow-only {
margin: 0 0 8px;
padding: 8px 10px;
border-radius: 6px;
font-size: 0.82rem;
}
.banner { background: #f2f3f5; color: #17171a; }
/* Deliberately overlapping, to show the boundary case. */
.narrow-only { display: none; background: #fdefec; color: #a3341f; }
.wide-only { display: none; background: #eaf6ef; color: #17734b; }
@media (max-width: 40em) {
.narrow-only { display: block; }
}
@media (min-width: 40em) {
.wide-only { display: block; }
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// Both bounds are inclusive, which is the whole point of this exercise.
const applies = (feature, bound, width) =>
feature === 'min-width' ? width >= bound : width <= bound;
test('min-width: 40em applies at 48em', applies('min-width', 40, 48), true);
test('and not at 32em', applies('min-width', 40, 32), false);
test('max-width: 40em applies at 32em', applies('max-width', 40, 32), true);
test('at exactly 40em, BOTH match', [applies('max-width', 40, 40), applies('min-width', 40, 40)], [true, true]);
test('so a shared bound double-applies, which is the bug', applies('max-width', 40, 40) && applies('min-width', 40, 40), true);
test('both queries are in the stylesheet, sharing the bound', (css.match(/40em/g) || []).length, 2);
test('and the later one wins at the boundary, by the cascade', css.indexOf('min-width: 40em') > css.indexOf('max-width: 40em'), true);
test('the base state hides both labels', (css.match(/display:\s*none/g) || []).length, 2);
Output
Both features are inclusive, so a max-width: 40em and a min-width: 40em query both match at exactly 40em and you get two conflicting sets of rules resolved by source order. It shows up as a layout that is briefly wrong at one specific width, which is miserable to reproduce. Two fixes: keep to one direction per stylesheet, which is what mobile first gives you for free, or make the upper bound max-width: 39.99em. Nothing here evaluates a query — the build has no viewport — so the arithmetic is done by the helper and the preview shows the effect.