Free, independent guides since 2010

Code

Media queries and container queries for responsive design

How to make layouts adapt with CSS media queries and container queries: breakpoints, mobile first, user preferences like reduced motion, and when container queries are the better choice.

<guide section="Code" type="guide" read="1 min"/>

Responsive design means one website that works on every screen. Flexible layouts with flexbox and grid do most of the work; media and container queries handle the rest.

Media queries, mobile first

CSS
.cards { display: grid; gap: 1rem; }               /* phones: one column */
@media (min-width: 40rem) { .cards { grid-template-columns: 1fr 1fr; } }
@media (min-width: 64rem) { .cards { grid-template-columns: repeat(3, 1fr); } }

Start with the small-screen layout and add complexity as space grows. Using rem units makes breakpoints respect the user’s font size.

User preference queries

CSS
@media (prefers-reduced-motion: reduce) {
  * { animation: none !important; transition: none !important; }
}
@media (prefers-color-scheme: dark) { /* dark theme */ }
@media (hover: hover) { .card:hover { transform: translateY(-2px); } }
@media print { nav, footer { display: none; } }

Reduced motion matters for people who get dizzy from animations – part of accessibility.

Container queries

A card may sit in a wide main column on one page and a narrow sidebar on another. Media queries only know the screen width; container queries know the space of the parent.

CSS
.card-wrap { container-type: inline-size; }
@container (min-width: 30rem) {
  .card { display: grid; grid-template-columns: 8rem 1fr; }
}

When to use which

SituationUse
Page layout: columns, navigationMedia queries
Reusable components in different placesContainer queries
Motion, colour scheme, printPreference media queries

Frequently asked questions

Which breakpoints should I use?

Let your content decide: add a breakpoint where the layout starts to look wrong, rather than copying device widths. A few well-chosen ones are enough for most sites.

Are container queries supported?

Yes, all current major browsers support size container queries.