Sub topic 4
Writing Media Queries
This chapter assumes you know basic HTML and CSS, including selectors and the box model. It also assumes you know the units px, rem, em, and %. You do not need to know any layout tools beyond that. By the end you will be able to write a media query, read one written by someone else, and avoid the errors that show up most often.
What a media query does
A media query is a condition attached to a block of CSS. The browser checks the condition against the current device and window. If the condition is true, the rules inside the block apply. If it is false, the browser ignores them.
Media queries only work as expected when the page is laid out at the real device width. Mobile browsers use a wide virtual viewport unless you tell them otherwise. Put this tag in the page <head>:
<meta name="viewport" content="width=device-width, initial-scale=1">Without it, a phone may lay the page out as if the screen were about 980 px wide. Your max-width: 600px rules would then never match.
The anatomy of a query
A media query has three parts:
- The
@mediakeyword. - An optional media type, such as
screenorprint. - One or more conditions in parentheses, called media features.
@media screen and (min-width: 48em) {
.layout {
grid-template-columns: 1fr 1fr;
}
}Here screen is the media type. (min-width: 48em) is the media feature. The rules in braces apply only when both are true.
You can usually leave out the media type. @media (min-width: 48em) applies to all media types, and this is the form most projects use.
The width features
The feature you will write most often is the viewport width. There are three ways to express it.
| Feature | Meaning | True when |
|---|---|---|
| `min-width: 48em` | At least this wide | Width is 48em or more |
| `max-width: 48em` | At most this wide | Width is 48em or less |
| `width: 48em` | Exactly this wide | Width is exactly 48em |
The exact form is almost never useful, because windows rarely sit at one exact width. Use min-width and max-width.
Modern browsers also support range syntax, which reads like a comparison:
@media (width >= 48em) {
.layout {
grid-template-columns: 1fr 1fr;
}
}
@media (48em <= width < 80em) {
.layout {
gap: 1.5rem;
}
}The first block matches the same widths as min-width: 48em. The second matches only the band from 48em up to, but not including, 80em. Range syntax is easier to read and avoids the off-by-one problem described later. Check browser support for your audience before relying on it, and use min-width if you need older browsers.
Combining conditions
You can combine conditions in three ways.
andrequires every condition to be true.- A comma means "or". A list of queries separated by commas matches if any one of them matches.
notnegates a whole query.
/* Both must be true: a tablet-sized band */
@media (min-width: 48em) and (max-width: 79.99em) {
.sidebar {
display: none;
}
}
/* Either may be true */
@media (max-width: 30em), (orientation: portrait) {
.banner {
padding-block: 0.5rem;
}
}
/* Negation applies to the whole query */
@media not print {
.print-only {
display: none;
}
}The not keyword negates the entire query that follows it, not just the first condition. Because of that, many authors avoid it in anything but simple cases.
Use em or rem, not px, in queries
Breakpoint values can be in px, em, or rem. Inside a media query, em and rem both refer to the browser's default font size, usually 16 px. They do not use any font size you set in your CSS. So 48em means 768 px at default settings.
The advantage appears when a user raises their default font size. A query written in em moves with it. At a 20 px default, 48em becomes 960 px, so the layout switches to wider columns later. That keeps line lengths comfortable for people who need larger text. A query written in px stays at 768 px, and the text can overflow its columns.
This tutorial uses em for breakpoints for that reason. Pick one unit and use it for every breakpoint in the project.
How the cascade treats queries
A media query does not add specificity. A rule inside a query has the same specificity as the same selector outside it. When two rules match with equal specificity, the one that appears later in the source wins.
That rule is the reason query order matters:
.card {
padding: 1rem;
}
@media (min-width: 48em) {
.card {
padding: 2rem;
}
}
.card {
padding: 0.5rem; /* This comes last, so it wins at every width. */
}The final .card rule overrides the query at every width, so the larger padding never shows. Keep each query after the base rules it modifies. The next chapter builds on this when it covers mobile-first CSS.
Features beyond width
Width is not the only thing you can test. Some other features are worth knowing now.
| Feature | Tests | Example |
|---|---|---|
| `orientation` | Whether the viewport is taller than wide | `(orientation: landscape)` |
| `resolution` | Pixel density of the screen | `(min-resolution: 2dppx)` |
| `prefers-reduced-motion` | The user's motion preference | `(prefers-reduced-motion: reduce)` |
| `prefers-color-scheme` | Light or dark system theme | `(prefers-color-scheme: dark)` |
| `hover`, `pointer` | Input capabilities | `(hover: hover)` |
User preference queries are a good use of media queries beyond layout. This one turns off a transition for people who asked their system to reduce motion:
.drawer {
transition: transform 0.3s ease;
}
@media (prefers-reduced-motion: reduce) {
.drawer {
transition: none;
}
}Input features such as hover and pointer get their own chapter later in this tutorial.
Where to put queries
There are two common ways to organize queries.
- Grouped at the end of the file. All queries for one breakpoint sit together. This is easy to scan by breakpoint, but a component's rules are split across the file.
- Next to the component. Each component has its base rules followed directly by its queries. This keeps one component's behavior in one place, at the cost of repeating the same
@medialine many times.
Either works. With plain CSS the second is easier to maintain, because you see everything a component does at once. Whichever you choose, keep every query after the base rules it changes.
Common errors
These are the problems you are most likely to meet.
- Missing viewport meta tag. Queries seem to be ignored on a phone. Add the tag shown at the start of this chapter.
- Gaps and overlaps between ranges. If one query uses
max-width: 48emand the next usesmin-width: 48em, both match at exactly 48em. If you usemax-width: 47.99emandmin-width: 48em, a width between 47.99em and 48em matches neither. Fractional widths happen on high-density screens and when users zoom. Range syntax with<and>=removes the problem:(width < 48em)and(width >= 48em)never overlap and never leave a gap. - Mixed units. Using
pxin one query andemin another makes breakpoints drift apart when the user changes text size. - Query written before the base rule. The base rule overrides it, as shown above.
- Missing parentheses.
@media min-width: 48emis invalid. The condition needs parentheses:@media (min-width: 48em). - Missing
and.@media screen (min-width: 48em)is invalid. Write@media screen and (min-width: 48em).
A browser that finds an invalid query does not apply the block at all, and it does not warn you on the page. Check the browser's developer tools if a block seems dead. The styles panel usually shows it struck through or missing.
Worked example
Suppose a page has a .layout that should be one column on small screens, two columns from tablet width, and three columns on desktop. This is the same pattern as the layout in the chapter's reference code. It uses min-width queries in em and sets a maximum width on large screens.
.layout {
display: grid;
gap: 1rem;
padding: 1rem;
}
/* Tablet and up */
@media (min-width: 48em) {
.layout {
grid-template-columns: 1fr 1fr;
}
}
/* Desktop and up */
@media (min-width: 80em) {
.layout {
grid-template-columns: 2fr 1fr 1fr;
max-width: 80rem;
margin-inline: auto;
}
}Here is how the browser reads it at different widths.
| Viewport width | Queries that match | Result |
|---|---|---|
| 400 px (25em) | None | One column from the base rules |
| 800 px (50em) | Tablet | Two equal columns |
| 1400 px (87.5em) | Tablet and desktop | Three columns, the desktop rule overrides the tablet one |
At 1400 px both queries match. The desktop block comes later, so its grid-template-columns wins. It does not add to the tablet value, it replaces it.
Checking your queries in the browser
You do not need a device to test a query. Open the browser's developer tools and turn on the responsive or device mode. Drag the viewport edge and watch the layout change. Most tools show the active width in pixels, so you can confirm a switch happens at the width you intended.
You can also test queries from JavaScript with window.matchMedia:
const query = window.matchMedia("(min-width: 48em)");
console.log(query.matches); // true or false right now
query.addEventListener("change", (event) => {
console.log(event.matches ? "Tablet or wider" : "Narrower than tablet");
});This is useful when behavior, not only styling, depends on the width. Prefer CSS where it is enough, because CSS needs no script and responds sooner.
Summary of decisions
- Always include the viewport meta tag.
- Use
min-widthfor most layout queries. Use range syntax where your browser support allows it. - Write breakpoints in
emorrem, and use one unit throughout. - Keep queries after the base rules they change.
- Use feature queries such as
prefers-reduced-motionfor user preferences, not only for size.
Exercise
A page has this CSS. At a viewport width of 900 px (56.25em), what padding does .card have, and why? Rewrite it so the tablet padding applies at that width.
.card { padding: 0.5rem; }
@media (min-width: 48em) { .card { padding: 2rem; } }
.card { padding: 1rem; }
Show answer
The padding is 1rem. The query matches at 56.25em, but the last .card rule has the same specificity and appears later in the source, so it wins at every width. Move the final rule above the query, or delete it: .card { padding: 1rem; } @media (min-width: 48em) { .card { padding: 2rem; } }. Now the base value is 1rem and the query raises it to 2rem from 48em up.
Exercise
You have @media (max-width: 48em) for one set of rules and @media (min-width: 48em) for another. What happens at exactly 48em, and how would you write the pair so no width matches both or neither?
Show answer
Both queries match at exactly 48em, so both sets of rules apply and the later one wins on conflicts. Use range syntax: @media (width < 48em) and @media (width >= 48em). Every width matches exactly one of them. Alternatively, write base rules for small screens and a single min-width: 48em query, which needs no max-width at all.