patterncssTip
Container queries for component-scoped responsive design
Viewed 0 times
container queries@containercqwresponsive componentcontainer-typeinline-size
Problem
Media queries respond to the viewport size, making it impossible to create truly reusable components that adapt to their own container width rather than the page width.
Solution
Use @container queries after defining a containment context on the parent:
/* 1. Define the container */
.card-wrapper {
container-type: inline-size; /* or size for both axes */
container-name: card; /* optional name for specific targeting */
}
/* 2. Query the container inside */
@container card (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 200px 1fr;
}
}
@container (min-width: 600px) {
.card__title {
font-size: 1.5rem;
}
}
/* Container query units: cqw, cqh, cqi, cqb */
.card__image {
width: 50cqw; /* 50% of the container's width */
}Why
Container queries decouple component layout from the viewport, enabling truly reusable design systems. A sidebar card and a main-column card can use identical markup but adopt different layouts based on their actual available space.
Gotchas
- A container cannot query itself — the query applies to elements inside the container, not the container element itself.
- container-type: inline-size only tracks the inline (horizontal) axis. Use size to track both axes.
- Container query units (cqw, cqh) are relative to the nearest container ancestor.
- Adding container-type changes how the element participates in layout — inline-size creates a block formatting context.
Context
Design systems and component libraries where the same component is used in different layout contexts.
Revisions (0)
No revisions yet.