A media query is an if for your CSS: “apply these rules only when this condition is true.”
@media (min-width: 768px) {
.sidebar { display: block; }
}
The rules inside the braces apply when the screen is at least 768px wide.
Try it
The Result panel is narrow, so this example uses 400px. Change the number and press Run.
<style>
.box { padding: 16px; background: #d0e8f2; color: #1a5276; font-weight: bold; }
@media (min-width: 400px) {
.box { background: #d94a00; color: #fff; }
}
</style>
<div class="box">Blue when narrow, orange when the panel is 400px or wider.</div>
The common conditions
| Condition | True when |
|---|---|
(min-width: 768px) | The viewport is 768px wide or more |
(max-width: 767px) | The viewport is 767px wide or less |
(orientation: landscape) | The screen is wider than tall |
(prefers-color-scheme: dark) | The visitor uses a dark theme |
(prefers-reduced-motion: reduce) | The visitor asked for less animation |
print | When printing the page |
You can combine conditions with and: @media (min-width: 600px) and (max-width: 900px).
Where to put them
Media queries can sit at the bottom of the stylesheet, or beside the rule they change. Either works. The important rule is the cascade: the media query rule has the same strength as the normal rule, so it has to come after it in the file to win.
.menu { display: none; }
@media (min-width: 768px) {
.menu { display: flex; } /* wins because it is later */
}
min-width or max-width?
Both are fine, but pick one direction and stay with it. Most developers choose min-width, which leads to the approach in the next lesson, Mobile First.
Mixing the two directions
max-width and some min-width queries is hard to follow, and queries can overlap or leave gaps. Stick to one.