Media Queries & Responsive Design

Responsive design makes one page work on every screen. Fluid layouts, flexible images and intrinsic techniques do most of the work; media queries step in where a layout needs to change shape at certain widths — or adapt to user preferences like dark mode and reduced motion.

Media query syntax

Try it yourself
Result

Rules inside @media (condition) apply only when the condition is true. The modern range syntax (width >= 600px) is clearer than the older min-width: 600px, which means the same thing; both work in all current browsers.

Mobile-first

Try it yourself
Result

Write the base styles for small screens first, then use min-width-style queries to add complexity as space grows. Small screens get the simplest CSS, and the code reads in order of increasing size.

Choosing breakpoints

Don't target specific devices — there are thousands. Instead, resize your browser until the design starts to look awkward, and put a breakpoint there. Many projects settle on a few, roughly:

WidthTypical layout
Under ~600pxSingle column (phones)
~600–1000pxTwo columns, sidebar may drop below (tablets, small laptops)
Over ~1000pxFull layout with a maximum content width

Using em units in media queries (width >= 40em) makes breakpoints respond to the user's text size as well.

Combining conditions

CSS combined.css
@media (width >= 600px) and (width < 1000px) {
  .sidebar { display: none; }
}

@media (orientation: landscape) and (height < 500px) {
  .site-header { position: static; }
}

@media (hover: hover) and (pointer: fine) {
  .card:hover { transform: translateY(-4px); }
}

@media print {
  nav, .ads { display: none; }
  a::after { content: " (" attr(href) ")"; }
}
FeatureDetects
width, heightViewport size
orientationPortrait or landscape
hover, pointerMouse vs touch
prefers-color-schemeLight or dark mode
prefers-reduced-motionThe user wants less animation
prefers-contrast, forced-colorsHigh-contrast settings
print, screenMedia type

User preferences

Try it yourself
Result

Fluid first, breakpoints second

Many layouts need fewer media queries than you'd expect. Prefer techniques that adapt continuously:

  • Grid with repeat(auto-fit, minmax(…, 1fr)) (lesson 29).
  • Flexbox with flex-wrap and a flex-basis (lesson 28).
  • clamp() for type and spacing (lesson 14).
  • max-width on images and containers.
  • Container queries for components (next lesson).

The viewport meta tag

None of this works on phones without the viewport meta tag in your HTML head:

HTML viewport.html
<title>Responsive</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

Testing

Use your browser's responsive design mode (Ctrl+Shift+M in Chrome and Firefox) to try many sizes, and check on real phones for touch behaviour and performance.

Try it yourself

Try it yourself
Result