Media Queries
Apply styles conditionally based on screen size.
Syntax
@media (min-width: 600px) { /* rules */ }A media query applies CSS only when a condition is true, most often the viewport width.
Use min-width for mobile-first designs and max-width to target smaller screens. Multiple breakpoints let a layout change several times.
Example
Loading editorβ¦
Press Run to see the result.
When to use it
- A developer uses @media (max-width: 768px) to collapse a horizontal navigation into a hamburger menu on mobile screens.
- A designer targets @media (prefers-color-scheme: dark) to automatically switch the site to a dark palette for users with OS dark mode enabled.
- A developer uses @media print to hide the navigation and sidebar, setting content to 100% width for clean print output.
More examples
Breakpoint for tablet and desktop
Progressively enhances a single-column mobile layout to two columns at 600px and three columns at 1024px.
/* mobile: single column */
.layout { display: block; }
@media (min-width: 600px) {
.layout {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 1024px) {
.layout {
grid-template-columns: repeat(3, 1fr);
}
}Dark mode with prefers-color-scheme
Swaps CSS custom properties in a dark-mode media query so the entire theme updates automatically when OS dark mode is active.
:root {
--bg: #fff;
--text: #1a1a2e;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #1a1a2e;
--text: #f0f0f0;
}
}
body { background-color: var(--bg); color: var(--text); }Print stylesheet hiding navigation
Hides navigation and ads, expands content to full width, and appends URLs after links for a clean print layout.
@media print {
.nav, .sidebar, .footer, .ads {
display: none;
}
.main-content {
width: 100%;
font-size: 12pt;
}
a::after {
content: ' (' attr(href) ')';
}
}
Discussion