With CSS media queries you can apply different styles based on a device's characteristics — screen size, resolution, orientation, and more. They're the backbone of responsive design: layouts that adapt and look good on any device.
The syntax
Here's the basic shape of a media query:
CSS@media screen and (min-width: 320px) and (max-width: 768px) {
/* a whole bunch of CSS */
}
Breaking it down:
- @media — every media query starts with this keyword.
- screen — the media type. Here we target devices with a screen (others include
printandall). - min-width — a media feature: a measurable property of the viewport.
- and / or / not — logical operators. not inverts a query, and requires every condition to be true, and a comma acts as or (at least one true).
There are many media features available — MDN keeps the full feature reference.
A simple example
Make the background green once the screen is at least 600px wide:
CSS@media screen and (min-width: 600px) {
div {
background: green;
}
}
Combining features
Chain conditions with and to target a range — green only between 600px and 900px, inclusive:
CSS@media screen and (min-width: 600px) and (max-width: 900px) {
div {
background: green;
}
}
You can experiment with plenty of features beyond width: orientation (landscape / portrait), resolution, any-hover, color, height, aspect-ratio, and more.
Nesting media queries
Queries can be nested. Below, a solid border appears on hover — but only on screens at least 600px wide and on devices that actually support hover (so it won't misfire on touchscreens):
CSS@media screen and (min-width: 600px) {
@media screen and (any-hover: hover) {
div:hover {
border: 10px solid black;
}
}
}
Inverting with not
Prefix a query with not to negate the whole thing. @media not screen and (min-width: 600px) means "apply when it's not a screen ≥ 600px" — which includes smaller screens, print, and so on, not simply a max-width.
CSS@media not screen and (min-width: 600px) {
div {
border: 10px solid black;
}
}
A note on sanity
Managing media queries can get unwieldy. When you're writing plain CSS, lean on a handful of standard device breakpoints and keep the number of queries to a minimum — fewer breakpoints, fewer places for bugs to hide. CSS-Tricks has a handy reference of media queries for standard devices.
Wrapping up
That's the core of media queries: the syntax, combining and negating features, and nesting. For the deep end, MDN's Using media queries guide is the canonical reference. Happy reading!