Container Queries
Use container queries so components adapt based on the size of their parent container instead of the full viewport.
Use container queries so components adapt based on the size of their parent container instead of the full viewport. This hands-on tutorial focuses on practical implementation of container queries concepts.
Container Queries
Media queries look at the viewport. Container queries look at the size of the component's container. This is powerful for reusable cards, widgets, and layouts placed in different regions of a page.
Start by Declaring a Container
.card-grid {
container-type: inline-size;
}
Once a parent becomes a query container, children inside it can react to that container width.
Query the Container
.product-card {
display: grid;
gap: 1rem;
}
@container (min-width: 30rem) {
.product-card {
grid-template-columns: 8rem 1fr;
align-items: center;
}
}
This means the card changes layout only when its own space grows, even if the full page stays the same.
Why This Matters
Container queries help when:
- a card appears in both sidebar and main content
- dashboard panels resize independently
- components are reused across different templates
Media Queries vs Container Queries
- use media queries for page-level layout shifts
- use container queries for component-level adaptability
Best Practices
- name containers intentionally when multiple nested components exist
- keep breakpoints tied to content needs, not arbitrary numbers
- combine with Grid and Flexbox for the cleanest responsive systems
Next Step
Continue to CSS Architecture and Scalability to organize large codebases without selector chaos.