Media queries (@media)
A media query applies a block of CSS only when a condition is true: the window width, the orientation, a dark theme or printing. Responsive design is built on them.
Syntax
@media (min-width: 768px) {
.cards { flex-direction: row; }
}
@media screen and (max-width: 600px) { … }
@media (width >= 768px) { … } /* range syntax */
@media (prefers-color-scheme: dark) { … } Media features and operators
| Syntax | What it does |
|---|---|
min-width | the window is at least this wide — the basis of mobile-first |
max-width | the window is at most this wide |
(width >= 768px) | range syntax from Media Queries 4, works in modern browsers |
orientation | portrait or landscape |
prefers-color-scheme | dark or light — the theme chosen in the system |
prefers-reduced-motion | reduce — the user asks for less animation |
screen / print | the media type: a screen or a printed page |
and | "and": all conditions must be true |
, | a comma means "or": one condition is enough |
not | negates the whole query |
Example
.cards {
display: flex;
flex-direction: column;
gap: 8px;
}
.cards div {
padding: 12px;
background: #e0f2fe;
border: 1px solid #0284c7;
}
@media (min-width: 600px) {
.cards {
flex-direction: row;
}
.cards div {
flex: 1;
}
} <p>Narrow window: cards in a column. Wider than 600px: in a row.</p>
<div class="cards">
<div>1</div>
<div>2</div>
<div>3</div>
</div> Result
Good to know
- Without <meta name="viewport" content="width=device-width, initial-scale=1"> in the <head>, a mobile browser lays the page out about 980px wide, and media queries for narrow screens don't work as expected.
- Mobile-first: base styles are for a narrow screen, and @media (min-width: …) adds changes for wider ones. The CSS stays simpler.
- Ranges must not overlap: (max-width: 767px) and (min-width: 768px), or the range syntax. With equal specificity the later rule wins.
- A media query looks at the window width, not the parent's; for the size of a container there are container queries (@container).
Sources and specification
- MDN: @media — MDN Web Docs
- Media Queries Level 4 (W3C) — W3C
See also
CSS Grid
CSS Grid lays out rows and columns: display: grid, grid-template-columns, fr, repeat() and minmax(), and a responsive grid without media queries.
The flex property
The CSS flex property is a shorthand for flex-grow, flex-shrink and flex-basis: what flex: 1, flex: auto and flex: none mean and how items share space.
The display property
The CSS display property sets how an element takes part in layout: as a block, inline with text, as a flex or grid container, or not at all. Values, examples.
Responsive image
How to give the browser several image variants for different screen sizes.
Responsive table
An overflow-x:auto wrapper for horizontal table scrolling on narrow screens.
The <meta> tag
charset, name/content, property, and http-equiv on the <meta> tag, with examples.