#testing#a11y

A Practical Guide to CSS Container Queries

· 3 min read

Every codebase has one area everyone is a little afraid to touch. On our team, it was everything related to container queries.

The first symptom was subtle. Nothing failed outright, but container queries kept drifting in the wrong direction, and every fix seemed to make the next one harder.

What was going wrong

Most of the complexity was accidental. Over the years we'd layered three different approaches to container queries on top of each other, and each one made sense at the time.

The setup was ordinary: Storybook at the edges, Astro doing most of the heavy lifting, and a handful of scripts nobody wanted to own. It worked well until usage roughly doubled over a single quarter.

What we changed

We started by writing down the one rule we actually cared about, then deleted every bit of code that didn't serve it. It's not glamorous, but it works.

Stripped of the project-specific bits, it looks like this:

.card-list {
  container-type: inline-size;
}

@container (min-width: 36rem) {
  .card {
    display: grid;
    grid-template-columns: 12rem 1fr;
    gap: 1.5rem;
  }
}

It's tempting to generalize this into a library. Resist that urge until you've needed it in at least three places.

A few things that helped along the way:

  • Pair on the first few changes so the knowledge doesn't live in one head.
  • Measure before and after, even if it's just a rough number in a spreadsheet.
  • Make the default the safe choice, not just the documented one.
  • Keep the old path around until the new one has survived a real incident.

Trade-offs

None of this is free. The new approach is a bit more verbose, and newcomers occasionally ask why we don't just use Playwright for everything. That's a fair question with a boring answer: we tried, and it made container queries harder to reason about.

There are cases where this falls apart. If your team is very small or your traffic is very spiky, the extra moving parts may not pay for themselves.

What's next

If you take one thing away from this, let it be this: container queries is a design decision, not a cleanup task. Make it early and make it on purpose.

OP
Owen Patel
Frontend engineer in Austin. Writing about frontend engineering.