Media queries are how CSS adapts a layout to different screen sizes. A media query tells the browser "only apply these rules if the viewport matches this condition" — most commonly a minimum or maximum width — which is the foundation of virtually every responsive website.
Without media queries, a layout built for a 1440px desktop monitor would look broken and cramped on a 375px phone screen. With them, you can rewrite specific rules at specific breakpoints while leaving the rest of your CSS untouched.
Basic Syntax
.container {
display: flex;
flex-direction: column;
}
@media (min-width: 768px) {
.container {
flex-direction: row;
}
}
By default, .container stacks its children vertically. Once the viewport reaches 768px wide or more, the second rule kicks in and switches it to a horizontal row — so the same markup produces a stacked layout on mobile and a side-by-side layout on tablets and up.
min-width vs max-width
min-width queries apply their styles once the viewport reaches at least that width — this is the basis of mobile-first design, where your default (unwrapped) CSS targets small screens, and each media query progressively adds rules for larger ones.
max-width queries apply once the viewport is no wider than that value — this is the basis of desktop-first design, where your default CSS targets large screens, and media queries override specific rules for smaller ones.
/* Mobile-first: base styles are for mobile, min-width adds to them */
.card { padding: 1rem; }
@media (min-width: 768px) { .card { padding: 2rem; } }
/* Desktop-first: base styles are for desktop, max-width overrides them */
.card { padding: 2rem; }
@media (max-width: 767px) { .card { padding: 1rem; } }
Both examples produce the same final result, but most modern CSS favors the mobile-first approach — see mobile-first responsive design for why.
Common Breakpoints
There's no single "correct" set of breakpoints, but a common starting point looks roughly like this: a small/mobile baseline with no query at all, min-width: 640px for large phones, 768px for tablets, 1024px for small laptops, and 1280px for desktops. Rather than targeting specific devices, pick breakpoints based on where your own content actually starts to look cramped or awkwardly spaced.
Querying More Than Width
Media queries aren't limited to width — (orientation: landscape), (prefers-color-scheme: dark) (covered in CSS dark mode), and (hover: hover) (useful for skipping hover-only styles on touchscreens) are all valid conditions. Multiple conditions can be combined with and:
@media (min-width: 768px) and (orientation: landscape) {
.hero { height: 60vh; }
}
This rule only applies when both conditions are true at once — a tablet in landscape mode, for instance, but not a phone in portrait mode even if it happens to be just as wide.
