Articles /

layout

Media queries: the complete guide

Media queries adapt your design to the user's device, preferences, and environment. Here is everything you need to use them well.

Width and height queries

The classic responsive breakpoint. Modern CSS supports range syntax for cleaner comparisons.

/* legacy syntax */
@media (min-width: 48rem) { /* tablet and up */ }

/* modern range syntax — cleaner and more readable */
@media (width >= 48rem) {
  .grid { grid-template-columns: repeat(2, 1fr); }
}

@media (48rem <= width <= 64rem) {
  .sidebar { display: none; }
}

Preference queries

Respect user preferences for color scheme, motion, contrast, and transparency.

@media (prefers-color-scheme: dark) {
  :root {
    --bg: oklch(15% 0.02 260);
    --text: oklch(92% 0.01 260);
  }
}

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    transition-duration: 0.01ms !important;
  }
}

@media (prefers-contrast: more) {
  :root { --border: oklch(0% 0 0); }
}
Always provide a prefers-reduced-motion rule. It is an accessibility requirement, not just a nice-to-have.

Hover and pointer queries

Detect whether the primary input device can hover and how precise it is. This is more reliable than checking width for touch vs. mouse.

/* only show hover effects when a hover-capable device is present */
@media (hover: hover) {
  .card:hover {
    box-shadow: 0 8px 24px oklch(0% 0 0 / 0.12);
  }
}

/* enlarge tap targets on coarse pointers */
@media (pointer: coarse) {
  .btn { min-height: 44px; min-width: 44px; }
}

Combining and nesting queries

Use and, or (comma), and not to compose complex conditions. With CSS nesting, you can inline media queries inside rule blocks.

/* combined */
@media (width >= 64rem) and (hover: hover) {
  .tooltip { display: block; }
}

/* nested inside a rule (native CSS nesting) */
.sidebar {
  display: none;

  @media (width >= 64rem) {
    display: block;
  }
}

Media queries vs. container queries

Media queries respond to the viewport. Container queries respond to a parent element's size. Use the right tool for the job.

  • Media queries: page-level layout shifts, user preferences, device capabilities.
  • Container queries: component-level layout changes that depend on the space available to that component.
  • You can combine both — a media query for the page shell, container queries for reusable components.

Best practices

  • Design mobile-first and add min-width breakpoints progressively.
  • Use rem breakpoints so they respect user font-size settings.
  • Prefer feature queries (@supports) over browser-sniffing hacks.
  • Limit breakpoints to 3-4; let flexible layout (Grid, Flexbox) handle the gaps.