media
@media
Applies contained CSS rules only when the specified media query matches the user's device, viewport, or environment. It is the foundation of responsive design and print-specific styling.
@media <media-query-list> { <rules> } Common conditions / descriptors
| Descriptor | Purpose |
|---|---|
| (min-width: 768px) | Match viewports at least 768px wide (mobile-first breakpoint) |
| (max-width: 767px) | Match viewports up to 767px wide (desktop-first breakpoint) |
| (prefers-color-scheme: dark) | Match users who prefer a dark UI theme |
| (prefers-reduced-motion: reduce) | Match users who requested reduced motion |
| (orientation: landscape) | Match landscape viewport orientation |
| Apply only when the document is being printed | |
| (hover: hover) | Match devices whose primary input can hover |
| (aspect-ratio: 16/9) | Match a specific viewport aspect ratio |
Examples
@media (min-width: 768px) {
.grid { grid-template-columns: repeat(3, 1fr); }
} Switch to a 3-column grid on tablet and up
@media (prefers-color-scheme: dark) {
:root { --bg: #0b0b0f; --fg: #f5f5f7; }
} Apply dark theme tokens when the OS is set to dark
@media print {
nav, .ads { display: none; }
body { color: #000; }
} Hide navigation and ads, force black text when printing
@media (min-width: 640px) and (max-width: 1023px) {
.sidebar { width: 240px; }
} Target a bounded tablet range using 'and'
Gotcha
Use mobile-first min-width queries so smaller screens get the default styles. Range syntax `@media (width >= 768px)` is now widely supported but check target browsers before dropping the legacy form.
Related at-rules
@container
Applies rules based on the size or style of a nearest containment context rather than the viewport, enabling truly component-scoped responsiveness. Requires an ancestor that opts in via container-type.
@supports
Applies rules only when the browser supports the tested CSS feature, enabling progressive enhancement without JavaScript. Conditions can be combined with and, or, and not.
@page
Styles the page box used when printing or generating paged media, controlling size, margins, and margin boxes like headers and footers. Selectors like :first, :left, :right, and named pages let you target specific pages.