Container Queries
Container queries allow a component to respond to the size of its containing element rather than the viewport. This is particularly valuable for reusable components that can appear in different parts of an application.
A card can therefore change its layout based on the width of the card's container rather than the entire browser window.
Container Query vs Viewport
Container Query
.card-list {
container-type: inline-size;
}
.card {
display: grid;
gap: 1rem;
}
@container (min-width: 500px) {
.card {
grid-template-columns: 160px 1fr;
}
}💡 The card changes layout when its containing component becomes wide enough.
Key Takeaways
- Container queries make components more context-aware.
- They reduce coupling between components and viewport breakpoints.
Knowledge Check
What is the major advantage of container queries?