Container Queries: Component-Responsive CSS
Media queries answer one question: how wide is the viewport? That was the only question for years, and it trained us to write responsive rules against the wrong subject. A card component does not care whether the browser is 1,200px wide; it cares how wide the card itself is â which depends on whether it sits in a sidebar, a dashboard cell, a modal, or a full-width feed. Reusing a component across those contexts meant either media queries that fired at the wrong times, or wrapper-specific override classes sprinkled through every consuming page. Container queries invert the reference: mark an element as a query container, and descendants style themselves against that container's size. The component finally carries its own responsive behavior, and the page that embeds it needs no CSS knowledge of what is inside.
The media query blind spot
Consider a product card that shows a horizontal layout above 420px and a stacked one below. With media queries, the 420px threshold refers to the window, so the card in a narrow sidebar stays horizontal (viewport is wide) and breaks, while the card in a full-width grid stacks too early (viewport was already past the breakpoint when the grid itself had not yet broken). You end up writing per-context media queries â .dashboard .card, .feed .card â until the component's styles are scattered. The root problem is that the viewport is a proxy for the condition you actually care about. Container queries remove the proxy: the same card checks its own inline size and works correctly in every host without a single host-specific rule.
Declaring a query container
container-type: inline-size is the entry point. It establishes a containment context on the element â the browser then guarantees the container's inline size is computed without depending on its descendants, which is what makes the query possible, and lays out contents under size containment on that axis. A query is written with the @container at-rule, optionally scoped to a named container:
.card-host {
container-type: inline-size;
container-name: card;
}
.product-card {
padding: 1rem;
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 14px;
}
.product-card .thumb {
aspect-ratio: 4 / 3;
width: 100%;
object-fit: cover;
border-radius: 10px;
}
.product-card .title {
font-size: 1rem;
font-weight: 600;
margin-block: 0.75rem 0.25rem;
}
@container card (min-width: 420px) {
.product-card {
display: grid;
grid-template-columns: 10rem minmax(0, 1fr);
gap: 1rem;
align-items: start;
}
.product-card .thumb { aspect-ratio: 1; }
}
@container card (min-width: 640px) {
.product-card {
grid-template-columns: 14rem minmax(0, 1fr);
padding: 1.25rem;
}
.product-card .title { font-size: 1.15rem; }
}
Select inside @container the same way you do in a media query; @container is a conditional group rule, so nesting, style queries, and custom property conditions all behave as you would expect. Important structural point: a query cannot match its own container â the rules inside apply to descendants only, which is exactly right for component self-styling. Anonymous containers work too â omit the name and the query resolves against the nearest ancestor with containment in scope â but naming prevents a parent up the tree from silently answering the question.
Choosing a container type
Three container types exist, and picking the wrong one costs performance:
| container-type | Queries allowed | Containment applied | Use when |
|---|---|---|---|
| inline-size | Inline (width) queries | Size containment on inline axis + style | Default for components; width drives layout |
| size | Both inline and block queries | Full size containment | Rare; block size must not depend on content |
| normal | Style queries only | Layout/style containment only | You only need style or state conditions |
inline-size is the sweet spot: block size still responds to content (so cards grow with text), while width â the axis layout decisions depend on â is queryable. Full size containment forces the element to size without any descendant contribution, which makes content-driven heights impossible; reserve it for fixed-geometry dashboards. The cost of setting container-type is not zero â containment changes how the browser can optimize layout â so apply it to the actual component boundary rather than to body or a page wrapper. One container per component root is the rule of thumb.
CQ units: sizing without a query
You do not always need a full query block. Container query units â cqi (1% of the container's inline size), cqb, cqh, cqw, and the small/large variants cqi-min, cqi-max â can be used anywhere a length is valid, immediately, without an @container rule. This is how you make type and spacing scale continuously with the component's own width instead of jumping at breakpoints:
.widget {
container-type: inline-size;
}
.widget .headline {
font-size: clamp(1rem, 0.7rem + 1.4cqi, 1.5rem);
}
.widget .body {
font-size: max(0.9rem, 1.1cqi);
line-height: 1.6;
}
.widget .actions {
display: flex;
flex-wrap: wrap;
gap: clamp(0.5rem, 1cqi, 1rem);
}
The mixed clamp() is the same fluid-type pattern from the units lesson, with cqi replacing vw â now the ramp is tied to the component, so a widget in a 300px drawer gets small type and the same widget in a 900px main column gets large type, with the window irrelevant. Discrete @container queries handle structural changes (stacked versus horizontal); cqi handles continuous refinement (type scale, padding, gaps). Mature component libraries use both: queries for layout mode, CQ units for tuning.
Scoping: nested containers and named queries
Containers nest â a dashboard card host inside a layout host â and an anonymous @container rule resolves against the nearest ancestor in scope, which may not be the one you meant. Names fix ambiguity: @container card (min-width: 420px) skips nearer unnamed containers and asks the one explicitly labeled card. You can also establish a container without immediately querying it, letting different subtrees answer different questions, and rename with container-name alone when the type was set by a shorthand (container: card / inline-size). For library authors, this means your component's internal queries always name its own container and never rely on proximity, so embedding the component inside another container â even a parent that also sets containment â cannot hijack the answers.
Fallbacks and support
Container queries are baseline widely available in current browsers, so the old advice of @supports (container-type: inline-size) progressive enhancement is mostly historical â but it remains correct for sites with long-tail enterprise browsers. The pattern: lay out a sensible stacked default that needs no query, then enhance with container rules. Since styles inside a query simply do not apply where the query is unsupported, the safe default is what renders. For CQ units, provide a plain rem fallback declaration first; unsupported engines ignore the later cqi line rather than miscomputing it. Also remember that container queries complement rather than replace media queries: viewport-level concerns (hiding a sidebar on mobile, switching page templates) stay with media queries, while component-internal decisions move to containers. The hybrid â media queries for page architecture, container queries for component internals â is the modern responsive contract.
Common Mistakes
Container query never fires
Fix: An ancestor must declare container-type: inline-size (or size) â without it there is no query container, and anonymous rules resolve against nothing
Rules inside @container style the container itself
Fix: A container query matches only descendants; style the container with plain selectors or a query on an outer container
Content height collapses or stops growing
Fix: Avoid container-type: size unless block size must be fixed â it applies full size containment; inline-size keeps content-driven heights intact
The wrong ancestor answers an anonymous query
Fix: Name your containers with container-name and write @container name (...) so proximity cannot pick a different ancestor
Best Practices
- Set container-type at the component boundary, not on page wrappers
- Use structural @container queries for layout mode switches and cqi units for continuous scaling
- Name containers in component libraries so embedding context cannot hijack queries
- Ship a sensible unqueried default so unsupported engines render correctly
- Keep viewport-level decisions in media queries; move component-internal decisions to containers
Interview Questions
Q1: How do container queries differ from media queries?
Media queries test the viewport (or a defined media condition), so results are identical for every instance on the page. Container queries test an ancestor element's own size, so two instances of the same component laid out differently on one screen can each pick the correct layout â component responsiveness without host-specific overrides.
Q2: What does container-type: inline-size actually do?
It establishes a query container with size containment on the inline axis: the container's inline size is computed independently of its contents, which is what makes width queries deterministic, while block size remains content-driven. That is why it is the default choice for cards and panels.
Q3: When would you use CQ units instead of an @container query?
When the change should be continuous rather than structural â font sizes, padding, and gaps that scale smoothly with the component's width. CQ units work anywhere a length is valid without a query block; use @container for discrete layout changes such as switching from a stacked to a horizontal card.
Key Takeaways
- Container queries make components respond to their own width instead of the viewport, eliminating host-specific overrides
- container-type: inline-size is the default declaration; @container rules style descendants, optionally scoped by name
- Container types trade capability against cost â inline-size for width, size for both axes, normal for style queries only
- cqi and sibling units provide continuous component-scale sizing with no query block
- Architecture split: media queries for page templates, container queries for component internals