Intermediate LevelCSS & Modern Layouts
What are CSS Container Queries and how do they differ from Media Queries?
❓ Interview Prompt: Explain @container rules, container-type, and why container queries enable truly reusable responsive components.
Media Queries respond to the viewport (browser window) width. Container Queries respond to a parent container's width. This is revolutionary for component-based design:
The Problem with Media Queries:
A card component styled with @media (min-width: 768px) behaves differently depending on where it's placed — a 300px sidebar vs a full-width area — because media queries only know the viewport.
Container Queries Solution:
Declare a containment context on the parent, then style children based on the container's size:
1
Parent:
container-type: inline-size — makes it a size query container.2
Child:
@container (min-width: 400px) { /* styles */ } — responds to the parent's width, not the viewport.Code Implementation Example
css
/* Parent establishes a container context */
.card-wrapper {
container-type: inline-size;
container-name: card;
}
/* Child responds to parent size, not viewport */
.card { display: flex; flex-direction: column; }
@container card (min-width: 400px) {
.card {
flex-direction: row;
align-items: center;
}
.card-image { width: 40%; }
.card-body { width: 60%; }
}💡Container query enabling responsive card layout based on parent width.
🎯 Interview Key Takeaway
Container queries make components self-responsive regardless of where they are placed in the page layout.
#Container Queries#Responsive#Components#Intermediate
Back to all CSS & Modern Layouts Questions→