Responsive and modern CSS
Container queries
Adapt a reusable component to the space provided by its own container instead of coupling it to the full viewport width.
8 minute lesson
A component may appear in a wide main area or a narrow sidebar on the same viewport. Container queries let it respond to that local space.
.card-wrapper {
container-name: card;
container-type: inline-size;
}
@container card (min-width: 30rem) {
.card {
display: grid;
grid-template-columns: 10rem 1fr;
}
}
The query evaluates a named eligible ancestor, not the viewport. The rules apply to descendants of that container, not the container itself. A wrapper is therefore useful when the component’s outer box establishes the query and its child changes layout.
Use media queries for page-wide environment decisions and container queries for reusable component layout. They complement each other.
Size containment prevents the queried dimension from depending normally on descendant sizes, avoiding a loop where the child changes the container that changes the child. Check that adding container-type does not alter a wrapper that previously relied on its contents for sizing.
Container query units such as cqi represent a percentage of the query container’s inline size. Use them with clamp() when a value should vary locally without becoming unbounded.
Place the same card in a sidebar and main column at one viewport width. Use the Container Queries panel to inspect which ancestor and threshold matched. The component should adapt differently without a viewport breakpoint.
Lesson completed