Adapt styles to viewport conditions and content breakpoints.
A media query applies styles when a condition matches, such as a minimum viewport width. It can also check print output or input features such as hover. The rules still follow the cascade.
.results {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 1rem;
}
@media (width >= 48rem) {
.results {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}The results use one column below the breakpoint and two at or above it. width tests the viewport. To respond to a component’s container instead, use a container query.
@media does not increase selector specificity. Here, the matching rule overrides the earlier column declaration because the selectors have equal specificity and the rule comes later.
| Condition | Matches |
|---|---|
(width >= 48rem) | At least 48rem; includes the boundary. |
(width < 48rem) | Below 48rem; excludes the boundary. |
(30rem <= width < 60rem) | At least 30rem, but below 60rem. |
(min-width: 48rem) | The same minimum threshold as width >= 48rem. |
(max-width: 48rem) | At most 48rem; includes the boundary. |
Both min-width and max-width include equality. In adjacent ranges, include the shared boundary on only one side. Safari versions before 16.4 ignore the comparison syntax. To support those releases at an inclusive lower boundary, use the equivalent min-width condition. Media query compatibility
For example, this adjusts spacing only in the middle range:
@media (30rem <= width < 60rem) {
.results {
gap: 1.5rem;
}
}In media query conditions, font-relative units use the initial font size rather than a font-size declaration on the page. With a 16-pixel initial size, 48rem is 768 CSS pixels. Changing the page's root font size does not itself move that threshold.
Use and when all conditions must match:
@media (hover: hover) and (pointer: fine) {
.link:hover {
text-decoration-thickness: 0.15em;
}
}This adds styles when the primary input supports hover and precise pointing. It does not tell you the device type or rule out touch input. Keep the link usable without hover.
A comma separates alternative media queries: the group matches if any listed query matches. A media type can also limit output, such as screen and (width >= 48rem) or print.
Resize until a real problem appears: navigation stops fitting, text becomes cramped, or an extra column has enough space to be useful. Add a rule for that change instead of copying a list of device widths.
Try it yourself
HTML + CSS