🍋
Menu
How-To Beginner 1 min read 258 words

CSS Container Queries: Responsive Components Guide

Use container queries to create truly responsive components that adapt to their container size.

Key Takeaways

  • Media queries respond to the viewport size — the entire browser window.
  • First, declare a containment context on the parent element: `container-type: inline-size` (track width) or `container-type: size` (track both dimensions).
  • A product card in a narrow sidebar (< 300px) stacks vertically: image on top, text below.
  • Media queries: "If the screen is narrow, stack these elements." Container queries: "If this component's container is narrow, stack these elements." Media queries require knowing where the component will be used.
  • Container queries are supported in all modern browsers (Chrome 105+, Firefox 110+, Safari 16+).

Beyond Media Queries

Media queries respond to the viewport size — the entire browser window. Container queries respond to the size of a parent element. This paradigm shift enables truly reusable components: a card component that layouts differently in a sidebar versus main content area, without knowing which context it's in.

Setting Up Container Queries

First, declare a containment context on the parent element: container-type: inline-size (track width) or container-type: size (track both dimensions). Optionally name it: container-name: card-wrapper. Then use @container to write size-based rules that apply when the container (not viewport) meets the condition.

Practical Examples

A product card in a narrow sidebar (< 300px) stacks vertically: image on top, text below. In a wide main area (> 600px), it layouts horizontally: image left, text right. With container queries, this single component adapts automatically without the parent needing to communicate its width through classes.

Comparison with Media Queries

Media queries: "If the screen is narrow, stack these elements." Container queries: "If this component's container is narrow, stack these elements." Media queries require knowing where the component will be used. Container queries work regardless of context. Use media queries for page-level layout decisions and container queries for component-level adaptations.

Browser Support and Adoption

Container queries are supported in all modern browsers (Chrome 105+, Firefox 110+, Safari 16+). For older browsers, they gracefully degrade to the default layout. Polyfills exist but add complexity. The progressive enhancement approach works well: design the default layout for the most common size, then add container query enhancements.

相关工具

相关格式

相关指南