
A media query applies CSS when conditions about the environment are true. Use media queries to adapt the layout when the content needs more space and to respect user preferences.
1. Width conditions
Minimum width and mobile-first CSS
.cards { display: grid; gap: 1rem; }
@media (min-width: 48rem) {
.cards { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}Start with the single-column layout. At 48 rem or more, the wider layout takes effect.
Maximum width and desktop-first CSS
@media (max-width: 40rem) {
.toolbar { flex-wrap: wrap; }
}A maximum-width query applies up to and including that width. If adjacent queries include the same boundary, both may apply there. Keep overrides intentional and test the boundary.
Combining conditions
@media (min-width: 48rem) and (orientation: landscape) {
.summary { max-width: 40rem; }
}Use viewport width rather than a list of device models. Choose a breakpoint where the content stops fitting comfortably. An external stylesheet can also be conditional through its link’s media attribute.
2. Choose a breakpoint by testing the content
Resize the browser gradually. Watch for text wrapping, overflowing controls, or an overwide line length. Compare before, at, and after the chosen breakpoint. Check the viewport meta tag if a mobile layout appears zoomed out.
3. Features other than width
| Feature | Example use |
|---|---|
orientation | Adapts when the viewport is portrait or landscape. |
hover and pointer | Adjusts interactions for the primary input mechanism. |
prefers-reduced-motion | Removes or reduces nonessential motion. |
prefers-color-scheme | Adapts to a light or dark preference. |
resolution | Tests pixel density where the presentation requires it. |
4. Logical operators
and requires all conditions to match. A comma separates alternative queries. Scope not carefully because it negates the query or condition it belongs to.
@media (prefers-reduced-motion: reduce) {
.card { animation: none; }
}Practice
Start with a single-column design. Add a second column only when its text and controls fit. Check the narrowest viewport and test reduced-motion settings if you add transitions.