CSS Container Queries for Responsive Components
How to use CSS container queries so components adapt to the space they actually get inside a sidebar, grid cell, or card — not just the viewport width.
Overview
Media queries only ever ask one question: how wide is the screen? That’s fine for page-level layout, but it breaks down for reusable components. A card placed in a 300px sidebar gets the same viewport rules as the identical card in a 1200px main column, so you end up writing overrides like .sidebar .card { ... } that couple the component to its context.
Container queries flip the question to: how much space does the component itself have? You mark a parent element as a containment context with container-type, and descendants can then react to that container’s size with @container. The same card can flip between a stacked and a horizontal layout whether it sits in a sidebar, a grid cell, or a modal, with no context-specific CSS and no JavaScript resize observers.
The result is components that are genuinely portable: you design them once, drop them anywhere, and they respond to the space they actually get.
When to Use
- Reusable components placed in different layout contexts (sidebar, main content, grid cell, modal)
- Cards that switch between horizontal and vertical layouts based on available width
- Navigation that collapses when its container is narrow, regardless of viewport size
- Dashboard widgets resized inside drag-and-drop grids
- Embeddable widgets that must adapt to an unknown host container
When NOT to Use
- Page-level layout: media queries are still the right tool for overall page responsiveness
- Fixed-width components: if a component always renders at the same size, container queries add nothing
- Style queries on a hard support deadline:
@container style()queries shipped later than size queries and have narrower coverage; check caniuse before relying on them - Situations where you can’t control the wrapper: container queries need a parent element you can mark with
container-type
Solution
Basic container query
Mark the wrapper, then query it from the component:
.card-container {
container-type: inline-size;
}
.card {
display: flex;
flex-direction: column;
gap: 1rem;
}
@container (min-width: 400px) {
.card {
flex-direction: row;
align-items: center;
}
}
When .card-container is at least 400px wide, the card switches to a horizontal layout. Below 400px it stays vertical, no matter what the viewport is doing.
Named containers
When containers nest, name them so a component can query a specific ancestor:
.sidebar {
container-type: inline-size;
container-name: sidebar;
}
.main-content {
container-type: inline-size;
container-name: main;
}
@container sidebar (min-width: 300px) {
.widget {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
@container main (min-width: 600px) {
.widget {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
}
Without a name, @container queries the nearest ancestor with a container-type, which is usually what you want, but names remove ambiguity.
Container query units
Container-relative units let typography and spacing scale with the container itself:
.panel {
container-type: inline-size;
}
.panel-title {
font-size: clamp(1rem, 5cqi, 2rem);
padding: 2cqb;
margin-bottom: 2cqh;
}
Available units:
cqw: 1% of the container’s widthcqh: 1% of the container’s heightcqi: 1% of the container’s inline sizecqb: 1% of the container’s block sizecqmin: 1% of the smaller dimensioncqmax: 1% of the larger dimension
Wrap them in clamp() to keep values inside sane bounds.
Responsive card component
A full three-breakpoint card that adapts to whatever slot it lands in:
.product-card-container {
container-type: inline-size;
padding: 1rem;
}
.product-card {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.product-card__image {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
}
.product-card__title {
font-size: 1rem;
}
@container (min-width: 350px) {
.product-card {
flex-direction: row;
gap: 1rem;
}
.product-card__image {
width: 150px;
aspect-ratio: 1;
}
.product-card__title {
font-size: 1.125rem;
}
}
@container (min-width: 600px) {
.product-card {
flex-direction: column;
}
.product-card__image {
width: 100%;
aspect-ratio: 16 / 9;
}
.product-card__title {
font-size: 1.25rem;
}
}
Note the middle breakpoint goes horizontal, then the wide one goes back to stacked with a bigger title: a real card often isn’t a simple small-to-large progression.
Navigation that adapts to its container
.nav-container {
container-type: inline-size;
}
.nav {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.nav__link {
padding: 0.5rem 1rem;
}
@container (max-width: 500px) {
.nav {
flex-direction: column;
}
.nav__link {
width: 100%;
text-align: center;
}
}
Container queries with CSS Grid
A grid that adds columns as its own width grows, useful when the grid sits inside a resizable panel:
.grid-container {
container-type: inline-size;
}
.grid {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
}
@container (min-width: 400px) {
.grid {
grid-template-columns: 1fr 1fr;
}
}
@container (min-width: 700px) {
.grid {
grid-template-columns: 1fr 1fr 1fr;
}
}
@container (min-width: 1000px) {
.grid {
grid-template-columns: repeat(4, 1fr);
}
}
Style container queries
Style queries react to computed values (custom properties) rather than size. Support is narrower than size queries, so treat them as progressive enhancement:
.theme-container {
container-type: style;
}
@container style(--theme: dark) {
.card {
background: #1a1a2e;
color: #e0e0e0;
}
}
@container style(--theme: light) {
.card {
background: #ffffff;
color: #1a1a2e;
}
}
Set the theme with a custom property:
<div class="theme-container" style="--theme: dark;">
<div class="card">Content</div>
</div>
For the viewport-level version of this theming pattern, see CSS Dark Mode with prefers-color-scheme.
Container queries in Tailwind CSS v4
Tailwind v4 ships container query variants natively: mark a wrapper with @container and use @sm:, @md:, @lg: modifiers:
<div class="@container">
<div class="card flex flex-col @md:flex-row @lg:flex-col">
<img class="w-full @md:w-36 @lg:w-full" src="product.jpg" />
<div class="@md:ml-4">
<h3 class="text-base @md:text-lg @lg:text-xl">Product Title</h3>
</div>
</div>
</div>
Explanation
container-type does two things at once. It establishes a query container that descendants can measure against, and it applies containment — with inline-size, the browser gets layout, style, and inline-size containment and can lay the box out without knowing how big its children are. That containment is what makes the queries resolvable, though it brings side effects worth knowing:
- A container’s size is determined by its context and content up to the point of containment. With
container-type: size, the element needs an explicit height (or a stretch context), otherwise it collapses to zero. position: fixeddescendants of a container are positioned relative to that container, not the viewport.- Percentage heights inside a container resolve against the container, which may differ from what legacy CSS assumed.
Media queries and container queries solve different layers of the problem:
A practical split: media queries for the page shell (columns, header, overall density), container queries for everything inside it. The same component then works in any slot the shell gives it.
| Media queries | Container queries | |
|---|---|---|
| Measures | Viewport | Nearest marked ancestor |
| Best for | Page layout, breakpoints | Reusable components |
| Setup | None | container-type on a parent |
| Context coupling | High (sidebar .card hacks) | None |
On support: size queries (inline-size, named containers, cq* units) are baseline across Chrome/Edge 105+, Safari 16+, and Firefox 110+, over 93% of global usage per caniuse. Style queries (@container style()) arrived later and are still catching up; gate them behind @supports or treat them as enhancement.
Variants
Using container queries with React
The CSS doesn’t change — the component just renders into a marked wrapper:
function ProductCard({ product }) {
return (
<div className="product-card-container">
<div className="product-card">
<img className="product-card__image" src={product.image} alt={product.name} />
<div>
<h3 className="product-card__title">{product.name}</h3>
<p>${product.price}</p>
</div>
</div>
</div>
);
}
// Same component works in any layout context — sidebar, grid, full width
function App() {
return (
<div className="layout">
<aside className="sidebar">
<ProductCard product={product} />
</aside>
<main className="content">
<ProductCard product={product} />
</main>
</div>
);
}
This replaces the common pattern of reaching for ResizeObserver or match-media hooks just to change a layout: the styling logic stays in CSS where it belongs.
Using container queries with Vue
Scoped styles work fine with container queries; the wrapper lives in the same component:
<template>
<div class="card-container">
<div class="card">
<img :src="product.image" :alt="product.name" />
<div class="card-body">
<h3>{{ product.name }}</h3>
<p>{{ product.price }}</p>
</div>
</div>
</div>
</template>
<style scoped>
.card-container {
container-type: inline-size;
}
.card {
display: flex;
flex-direction: column;
}
@container (min-width: 400px) {
.card {
flex-direction: row;
}
}
</style>
Best Practices
- Prefer
container-type: inline-sizefor most cases: you almost always want to react to width, and it avoids the height-collapse trap ofsize - Name containers (
container-name) when components nest and you need to target a specific ancestor - Set
container-typeon the parent wrapper, not the component itself: a component can’t query its own size - Use container query units (
cqi,cqw) for typography that scales with the container; pair withclamp()for min/max bounds - Stay
min-width-first: write the narrow layout as the default and layer wider@container (min-width: ...)rules on top, same mobile-first logic as media queries. Reach formax-widthqueries only for desktop-first code you’re retrofitting - Test components in narrow containers, not just narrow viewports: a 200px sidebar breaks different things than a 375px screen
- For a deeper grounding in the layout primitives these examples use, see the Complete Guide to CSS Grid and Flexbox
Common Mistakes
- Setting
container-typeon the component instead of its parent: a component queries its container, so the marker has to go one level up. - Using
container-type: sizewithout a height:sizecontains both axes, so without a defined height the element collapses to zero. Stick withinline-sizewhen you only need width queries. - Assuming container queries replace media queries: they solve different layers. Keep media queries for page layout, container queries for components.
- Nesting containers too deep: each
container-typecreates a containment context and unnamed queries hit the nearest one, and deep nesting makes behavior hard to predict. - Forgetting containment side effects:
position: fixedchildren anchor to the container, not the viewport, which surprises people migrating modals or sticky headers. - Only testing at container-friendly widths: a component that looks fine full-width can break in a narrow sidebar.
See Also
- MDN — CSS container queries
- MDN — CSS containment
- web.dev — Container queries
- caniuse — CSS container queries
- Companion resources — runnable HTML demo: one card adapting to two differently-sized containers
Frequently Asked Questions
What browser support do container queries have?
Size container queries work in Chrome/Edge 105+, Safari 16+, and Firefox 110+, over 93% of global usage according to caniuse. Style queries (@container style()) have narrower support, so check caniuse and treat them as progressive enhancement. For older browsers, wrap the query in @supports and provide a media-query fallback.
How are container queries different from media queries?
Media queries measure the viewport; container queries measure the component's own container. A card in a 300px sidebar on a 1920px screen sees 300px, not 1920px, which is exactly what a reusable component needs to know.
Can I use container queries with CSS frameworks?
Yes. Tailwind CSS v4 includes container query support via the @container class and variants like @sm:, @md:, @lg:. In v3 you needed the @tailwindcss/container-queries plugin. Other frameworks may need custom CSS.
What's the difference between container-type: inline-size and container-type: size?
inline-size contains only the inline axis (width, in horizontal writing modes), the common case. size contains both axes and requires the container to have a definite height, or it collapses to zero. Default to inline-size.
How do I provide a fallback for older browsers?
Gate the query with @supports and fall back to a media query:
.card { flex-direction: column; }
@supports (container-type: inline-size) {
.card-container { container-type: inline-size; }
@container (min-width: 400px) {
.card { flex-direction: row; }
}
}
/* Fallback for browsers without container queries */
@media (min-width: 768px) {
.card { flex-direction: row; }
}
Do container queries hurt performance?
Containment usually helps rendering: the browser can lay out a container independently of the rest of the page. The cost is in deeply nested containment contexts, so keep the tree shallow and mark only the wrappers that need it.
Related Resources
Design Tokens with CSS Custom Properties
How to build a design token system with CSS custom properties: color scales, semantic tokens, spacing, typography, dark themes, and responsive scaling.
RecipeDark Mode with prefers-color-scheme and CSS Variables
How to implement dark mode using CSS prefers-color-scheme media query, CSS custom properties, and manual toggle with localStorage persistence.
GuideMobile Responsive Design: Diagnose and Fix Layouts
Diagnose production responsive failures, choose the right reaction strategy, and verify fixes with measurable overflow, image, CLS, and viewport tests.
RecipeReactive State Management with Svelte Stores
How to manage reactive state in Svelte using writable, readable, derived stores, and custom stores with contract-based updates.
RecipeData Fetching with Vue 3 Composition API
How to fetch and manage data in Vue 3 using the Composition API with ref, computed, watch, and composables for reusable data logic.
GuideComplete Guide to CSS Grid and Flexbox
Master CSS layout: Grid vs Flexbox, template areas, subgrid, container queries, logical properties and responsive patterns without media queries.