@media
Applies rules only under given conditions — the window width, the system theme and others.
Syntax
@media (min-width: 600px) { … }Parameters
| Parameter | Type | Description |
|---|---|---|
| min-width | length | The rules apply if the window is at least this wide. |
| max-width | length | The rules apply if the window is at most this wide. |
| prefers-color-scheme | light | dark | The theme chosen in the user's system. |
| prefers-reduced-motion | reduce | The user asked to reduce animations. |
| hover | hover | none | Whether the main input device can hover (a mouse can, a finger cannot). |
Examples
One column on a narrow screen, three on a wide one:
<style>
.cards { display: grid; gap: 8px; }
.cards div { padding: 12px; background: lightskyblue; }
@media (min-width: 500px) {
.cards { grid-template-columns: repeat(3, 1fr); }
}
</style>
<div class="cards"><div>1</div><div>2</div><div>3</div></div>A dark theme by the system setting:
<style>
.theme { padding: 12px; background: white; color: black; }
@media (prefers-color-scheme: dark) {
.theme { background: #222; color: white; }
}
</style>
<div class="theme">This block follows the system theme.</div>Notes
Write the styles for a phone first and extend them for wide screens in min-width media queries — this takes less code. The modern range syntax is also supported: @media (width >= 600px). To adapt a component to its container rather than the window, use @container.
See also
- @container — Applies rules depending on the size of a container rather than the window.
- max-width — The maximum width: the element can be narrower, but never wider.
- grid-template-areas — Draws the grid layout as a map of named areas.
- @supports — Applies rules only if the browser supports a given property, value or selector.
Related recipes
- How to add print styles
- How to add the viewport meta tag for mobile
- How to make a dark theme
- How to make a page responsive
- How to make a responsive navigation
- How to make a sidebar layout
- How to make two columns
- How to respect reduced motion
- How to show an element only on mobile or only on desktop
- How to show different images on different screens
- How to stack columns on mobile
- How to use container queries
- How to use media queries
In the tutorial
- Media queries — Responsive layout with media queries — the viewport tag, the @media rule, min-width and max-width, the mobile first approach and rebuilding the skeleton.