Responsive and modern CSS
Media queries
Apply styles when viewport or user media features match and choose content-driven breakpoints instead of device labels.
8 minute lesson
A media query conditionally applies a block of CSS:
.hero {
display: block;
}
@media (min-width: 48rem) {
.hero {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
This is mobile-first: the simple layout is the default, and the enhanced layout begins when enough space exists.
Choose the breakpoint where the content needs to change, not because a device list calls it “tablet.” A rem breakpoint follows the browser’s initial font-size reference, including user defaults, rather than a font size you later set on html.
Media queries can also detect preferences and capabilities:
@media (prefers-reduced-motion: reduce) { }
@media (prefers-color-scheme: dark) { }
@media (hover: hover) and (pointer: fine) { }
@media print { }
Do not infer a whole device from one capability. A laptop may have both touch and a trackpad. Build the essential interaction for every input, then use a query for a genuine enhancement such as hover feedback.
In DevTools, drag the viewport until the layout—not the ruler—looks constrained. Record that width, test just below and above it, then emulate reduced motion, dark color scheme, and print. A query is correct only if both branches remain complete and usable.
Lesson completed