CSS Container Queries let developers style elements based on the size of their own container rather than the viewport.
What are Container Queries?
Container queries work like media queries, but they react to the dimensions of a specific element. This enables components to adapt automatically when placed in different layout contexts.
- Triggered by the inline‑size or block‑size of the nearest container.
- Declared with the
@containerrule - see MDN for syntax. - Can be scoped to a named container for predictable behavior.
- Reduce the need for multiple component variants tied to viewport breakpoints.
- Work alongside existing CSS features such as CSS containment.
Defining a Container Element
Before a component can be queried, its parent must be marked as a container. This is done with the container-name and container-type properties.
- Choose a semantic name, e.g.,
article, to avoid confusion. - Set
container-type: inline-sizefor width‑based queries (most common). - Optionally use the shorthand
container: name / typefor brevity. - Apply the container to a block‑level element such as
li.article-container. - Remember that the container does not affect layout by itself - it only enables queries.
Writing Container Queries
Container queries resemble media queries in structure, but they reference the defined container. You can write as many as needed to cover various size ranges.
- Basic syntax:
@container (width: 600px) { … }for the nearest container. - Named syntax:
@container article (inline-size > 500px) { … }. - Use logical operators (
and,or) to combine conditions. - Target child elements inside the query block to adjust grid, typography, or spacing.
- Keep queries atomic - each one should handle a single layout shift.
Combining Container and Media Queries
Container queries do not replace media queries they complement them. Media queries still handle global conditions like device orientation.
- Wrap container queries inside a media query to limit execution to certain devices.
- Use media queries for fallback styles when the container feature is unavailable.
- Prioritize container queries for component‑level changes, media queries for page‑level adjustments.
- Test combinations to avoid conflicting rules.
- Reference best practices in related workflow article.
Browser Support and Fallback Strategies
All major browsers now implement container queries, but older versions may lack support. Provide graceful degradation to ensure usability.
- Check support with
@supports (container-type: inline-size)before applying queries. - Supply equivalent media‑query rules inside the
@supports notblock. - Use feature‑detection libraries such as Modernizr for older browsers.
- Document fallback behavior for editors, linking to GitHub subissues guide for version tracking.
- Monitor updates via the Tech Insights feed.