CSS3 & Modern Layouts (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What are Container Queries (`@container`) vs. Media Queries (`@media`)?
senior LevelCode ExampleDocker & ContainersSystem Design
In Simple Words:
- Media Queries (
@media (min-width: 768px)): Inspect the width of the entire browser viewport.- The Problem: A card component rendered inside a narrow 300px sidebar on desktop will trigger desktop media queries and break layout!
- Container Queries (
@container):- The component inspects the width of its immediate parent container, not the browser viewport!
- Enables true modular, context-independent UI components.
css
/* 1. Define container context on parent */
.sidebar, .main-feed {
container-type: inline-size;
container-name: card-container;
}
/* 2. Card styles based on available parent space */
@container card-container (min-width: 450px) {
.user-card {
display: flex;
flex-direction: row; /* Horizontal when container > 450px */
}
}