Introduction to CSS Container Queries
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
The Problem Container Queries Solve
A media query only knows about the size of the whole browser viewport. But a reusable component - a card, for instance - might be placed in a wide main column in one part of a page, and a narrow sidebar in another. A media query cannot tell the difference; a container query can.
Step 1: Declare a Containment Context
.card-wrapper {
container-type: inline-size;
container-name: card;
}container-type: inline-size tells the browser to track this element's own width so descendants can query it. container-name is optional but useful once multiple containers are nested and a query needs to target a specific one.
Step 2: Write the Container Query
@container card (min-width: 400px) {
.card-title {
font-size: 1.5rem;
}
}This rule only applies when the .card-wrapper container itself is at least 400px wide - regardless of how wide the overall browser window is.
Why This Changes Component Design
A single card component can now genuinely adapt to wherever it is placed - full width, half width, or squeezed into a narrow sidebar - without needing separate variants or knowledge of the surrounding page layout. This makes components far more reusable across different parts of a design.
A Small Working Example
.card {
display: flex;
flex-direction: column;
}
@container card (min-width: 350px) {
.card {
flex-direction: row; /* switches to a side-by-side layout once roomy enough */
}
}