Media Queries
Optimizing media queries
What matters
- Content — set MQs tailored to the content.
- Readability — make it obvious what MQs do.
- Maintainability — make MQs easy to change/remove.
What doesn’t matter
- Number of total MQs.
- Number of repeated MQs.
- Number of unique MQs.
Media queries are not a performance bottleneck for the browser. Don’t pretend you need to fix this.
Breakpoints in a design system
Sometimes it makes sense to abstract breakpoint values
GravDept writes media queries for
- Adapt
Where to write media queries
Grouping all media queries at the end.
Grouping all rules into the same media query expression.
Grouping all media queries with the component they affect.
Volume
It doesn’t matter how many media queries a website uses. At all. Write as many as you need.
There is no
Choosing breakpoints
MQs in practice
Writing better media queries
1. Mobile first
The first media query is no media query. Ethan Marcotte
2. Use pixel units
Use pixel px
units for simplicity and precision:
// Good
@media (min-width: 1000px) {}
// Bad
@media (min-width: 10cm) {}
@media (min-width: 100em) {}
Don’t use absolute units (cm
, mm
, in
, pt
, pc
).
Don’t use relative units (em
, rem
). Circ a 2012, browser-level zooming was inconsistent and Cloud Four showed em
-based media queries were more consistently than pixels. This problem has been fixed.
See #3 — Pixels guarantee precision when shielding breakpoints. Relative units will freqently have rounding errors.
3. Shield breakpoints
When min/max media queries share a boundary, make sure they are offset by one pixel:
// Good
@media (max-width: 999px) {}
@media (min-width: 1000px) {}
// Bad
@media (max-width: 1000px) {}
@media (min-width: 1000px) {}
This prevents both MQs from applying unexpectedly at the exact breakpoint.
4. Abstract boundaries to variables
Even better, create $bp-{context}
variables to allow the breakpoint abstraction to changed everywhere at once.
@media (max-width: $bp-box - 1px) {}
@media (min-width: $bp-box) {}
A solid example
MQs in action with several good practices in use:
// ==============================================
// Box
// ==============================================
.box {
padding: 10px;
border: 1px solid $c-border;
}
// ----------------------------------------------
@media (max-width: 999px) {
.box {}
}
// ----------------------------------------------
@media (min-width: 1000px) {
.box {}
}