๐Ÿ“ฑ Responsive Design

CSS Container Queries: Responsive Components, Not Just Pages

By Shubham Sharmaยทยท8 min read
Card component resizing based on its container width

I hit the wall that container queries were built to solve on a Laravel dashboard I shipped last year: the same product-card component looked perfect in the main grid, then squished into a mess the moment I dropped it into a narrow sidebar on the same viewport. Media queries couldn't help โ€” the viewport hadn't changed, only the card's container had. I ended up shipping two nearly-identical CSS classes just to make it work. If container queries had been in my toolbelt, that whole hack would have collapsed into six lines. Now that they're supported everywhere, they're one of the first tools I reach for whenever a component has to live in more than one layout.

Step 1: declare a container

.card-wrap {
  container-type: inline-size;
  container-name: card;
}

Step 2: query it

.card { display: block; }

@container card (min-width: 400px) {
  .card { display: grid; grid-template-columns: 120px 1fr; gap: 1rem; }
}

Container queries vs media queries

  • Media query โ€” based on viewport
  • Container query โ€” based on a parent element's size
  • Use container queries for reusable components that live in multiple layouts

Container query units

cqw, cqh, cqi, cqb let you size things relative to the container itself โ€” perfect for fluid typography inside a card.

.card h2 { font-size: clamp(1rem, 5cqi, 1.75rem); }

Common gotchas

  • A container queries its size โ€” you can't size the container based on its children inside the same query
  • container-type: inline-size only watches width; use 'size' for height too
  • Don't over-name containers โ€” naming is optional

Frequently asked questions

Are container queries supported everywhere?

Yes โ€” all major evergreen browsers (Chrome, Edge, Firefox, Safari) support them. Old IE is the only thing that doesn't, and that's been gone for years.

Should I replace all media queries?

No. Use media queries for page-level layout and container queries for component-level layout.

Enjoyed this article?

Share it with a fellow developer or explore more tutorials in our blog.

More articles

Related articles