CSS Media Queries: Responsive Design for Every Screen
People will open your page on a 360-pixel phone and on a 2560-pixel monitor. A media query applies a block of rules only when a condition about the device or the user's settings is true. It is the backbone of responsive design.
Syntax
.cards { display: grid; gap: 1rem; }
@media (min-width: 700px) {
.cards { grid-template-columns: 1fr 1fr; }
}
Below 700 pixels the cards stack in one column; at 700 and above they form two. Rules inside the @media block follow normal cascade rules, so they override earlier rules of equal specificity because they come later.
Mobile first
Write the base styles for small screens, then add complexity with min-width queries as space grows. Small screens get the simplest CSS, and you rarely need to undo anything. The opposite approach, desktop first with max-width queries, tends to pile up overrides. Pick breakpoints where your content starts to look cramped or stretched, not at the sizes of particular phones.
The viewport meta tag
Without this line in the HTML <head>, mobile browsers pretend to be about 980 pixels wide and zoom out, and your queries never fire:
<meta name="viewport" content="width=device-width, initial-scale=1">
User preference queries
Media queries also read settings people choose in their operating system:
(prefers-color-scheme: dark): the user wants a dark theme.(prefers-reduced-motion: reduce): the user has asked for less animation, often because motion makes them unwell. Turn off large animations in this case.(hover: hover): the main input can hover, so hover-only effects are safe.
Try it
The example has a box that changes color at 600 pixels. JavaScript's matchMedia() evaluates the same query, and the script prints whether it matches. Our test suite runs the example in a 1280-pixel-wide window, so the expected output says it matches. In the narrow preview on a phone, it may not: that difference is exactly what a media query is for.
Expected page text
Yellow on narrow screens, green from 600px up. (min-width: 600px) matches: true
Change 600px to 2000px and run it again to see the query switch off.
Common mistakes
- Forgetting the viewport meta tag, so phones never reach your small-screen styles.
- Putting a query before the base rule it should override; order still matters.
- Writing
@media min-width: 700pxwithout parentheses around the condition.
Summary
@media (condition) { ... }applies rules only when the condition holds.- Go mobile first with
min-widthbreakpoints chosen by your content. - Respect
prefers-reduced-motionandprefers-color-scheme.
Quiz: Media queries