What are Container Queries?
Media queries are based on the viewport size. Container queries allow elements to adjust their layout based on the size of their parent container rather than the viewport.
This is a game changer for reusable components. A component like a product card can finally know if it is placed in a narrow sidebar or a wide grid and style itself accordingly.
Example
.product-grid {
container-type: inline-size;
container-name: sidebar;
}
@container sidebar (max-width: 400px) {
.product-card {
flex-direction: column;
}
}
Key takeaways:
- You must explicitly define a container type.
- Container queries use the
@containerrule instead of@media. - They make component-driven architecture more robust.