Style components based on their parent container, not the viewport
📚 Theory: What Are Container Queries?
The Problem with Media Queries
Media queries look at the viewport (browser window
size). This works for page layout, but fails when you have a component
that needs to behave differently depending on WHERE it is placed on
the page.
Example Problem
Imagine a product card that should be horizontal in the main content
but vertical in the sidebar. Media queries cannot detect that the card
is in a narrow sidebar — they only know the screen size is 1200px.
The Solution: Container Queries
Container queries look at the parent element's size,
not the viewport. This means a component can adapt to its container,
making it truly reusable.
All modern browsers support container queries. You can use them today!
1. Same Card, Different Containers
The same card component is placed in two different containers. Resize
your browser to see how the card changes based on its container width!
🖼️
Sidebar Card
This container is narrow, so the card stays vertical
(column).
🖼️
Main Content Card
This container is wide, so the card becomes horizontal (row)
using container query!
💡 Notice: The card in the sidebar is vertical. The
card in the main content is horizontal. Same HTML, same CSS, different
containers — different layouts. This is impossible with media queries!
/* Looks at VIEWPORT (screen size) */ @media (min-width: 768px) {
.card { display: flex; } } /* Problem: Card in sidebar and card in
main content behave the same way */
✅ Container Query
/* Looks at PARENT CONTAINER */ .card-container { container-type:
inline-size; } @container (min-width: 400px) { .card { display:
flex; } } /* Card adapts to its container! Sidebar card stays
vertical, Main card becomes horizontal */
4. Practical Use Cases
Product cards — vertical in sidebar, horizontal in
main content
Navigation menus — vertical in mobile drawer,
horizontal in header
Dashboard widgets — different layouts based on
widget size
Email components — adapt to different email clients