About

CSS Container Queries: Styling by Parent Size, Not Viewport

How they differ from viewport-based media queries

Media queries only respond to viewport size, which has limitations when the same component needs to look different in a sidebar versus the main area. Container Queries apply @container rules based on the size of a parent declared with container-type.

This enables truly component-based design where reusable components respond correctly regardless of their placement.

How to Apply

1

Declare container-type: inline-size on the parent element

2

Optionally assign a name with container-name

3

Write container-size-based styles with @container rule

4

Gradually migrate from existing media query responsive code

Pros

  • ✓ Components respond independently of placement
  • ✓ Reduces media query dependency for cleaner code

Cons

  • ✗ container-type creates new formatting context which may affect layout
  • ✗ Nested container queries can be difficult to debug

Use Cases

Dashboard widgets auto-adapting based on placement area Reusing design system components in various contexts

References

← What Is CSS Subgrid? Aligning Card Contents to the Parent Grid What Is CSS :has()? Styling Parents Without JavaScript →