Media queries respond to viewport size, but components often need to adapt based on their container. A card component might appear in a narrow sidebar or wide main content area. Container queries finally solve this problem, enabling components that respond to their immediate context.
Container Query Fundamentals
Container queries require establishing containment context on parent elements. Children can then query their container's size using @container rules. This enables component libraries that work consistently regardless of where components are placed.
- Define containment with container-type: inline-size on parent elements
- Use @container rules to style based on container width
- Name containers for explicit targeting in complex nested scenarios
- Combine with CSS Grid and Flexbox for powerful responsive layouts
- Browser support is now excellent—safe for production use
Practical Applications
Card components adjusting layout based on available width represent the classic use case. Navigation components can switch between horizontal and vertical layouts. Data tables can show or hide columns based on container space. These patterns create truly portable, reusable components.