Container components
Build reusable components with container queries.
A reusable component
Picture a card component: the same card should look wide in the main column, narrow in a sidebar, medium in a modal. Media queries watch the screen, so one CSS cannot cover all three. Container queries encapsulate the component so it listens only to the box it lives in.
The component then adapts to where it is placed. The same HTML and CSS produce different looks in different containers; reuse goes up.
Encapsulation and isolation
A container component is somewhat resistant to outside styles. Its inner @container queries look only at the component's own container; a font size or color coming from a parent does not break inner queries.
This brings consistency to a design system. When the team works on a component, they read its behavior in different containers from the component file; no need to look elsewhere.
Exercise A reusable card component
Give the .product selector container-type: inline-size and container-name: product. Then, inside an @container product (min-width: 320px) query, set display: grid on the .product-body sub-selector. The product card lays out as one column when narrow and a grid when wide.
Show example solution
/* open the product card container and name it */
/* switch the body to a grid in wide containers */
.product {
container-type: inline-size;
container-name: product;
}
@container product (min-width: 320px) {
.product-body {
display: grid;
}
}
Test yourself
-
What is the core benefit of container components?
- The same component looks different in different containers
- Less HTML is written
- JavaScript runs faster
- Browser memory drops
Show answer
The same component looks different in different containers — Correct. The component adapts to its container, not the screen width.
-
Define the component container
.product { container-type: ____; container-name: product; }Show answer
.product { container-type: inline-size; container-name: product; } -
Match component concepts
- Encapsulation
- Component listens to container
- Not inheritance
- Looks at container not parent
- Reuse
- Same CSS in different containers
- Responsive
- Adapts to the container