Sub topic 1
Why Viewport Media Queries Fall Short for Components
Prerequisites
Assume you know CSS selectors, the cascade, the box model, and basic flexbox or grid layout. You should also understand @media queries and CSS custom properties.
Why Viewport Media Queries Fall Short for Components
A viewport media query compares styles with the browser window. That works well for page-level changes, such as switching a navigation bar at a narrow screen width.
Reusable components often live in different contexts. The same card might appear in a wide main column, a narrow sidebar, or a two-column grid. The viewport can remain unchanged while the card's available width changes. A viewport query cannot detect that local change.
@media (min-width: 50rem) {
.card {
grid-template-columns: 8rem 1fr;
}
}This rule makes every .card use two columns when the viewport reaches 50rem. A card inside a narrow sidebar may still be too small for that layout.
The Container Query Idea
A container query compares a component with the size of an ancestor that you designate as a query container. The component can then adapt to the space it actually receives.
flowchart TD
A[Viewport] --> B[Page layout]
B --> C[Query container]
C --> D[Component]
D --> E{Container width}
E -->|narrow| F[Single column]
E -->|wide| G[Two columns]caption: A component responds to its query container rather than directly to the viewport. alt: A viewport contains a page layout, which contains a query container and a component. The component chooses a narrow or wide layout from the container width.
Declaring a Container with `container-type`
Set container-type: inline-size on the ancestor. This enables queries about its inline size, which is usually its width in a left-to-right writing mode.
.card-wrapper {
container-type: inline-size;
}
.card {
display: grid;
gap: 1rem;
}The wrapper becomes the query container. The declaration also adds containment, which lets the browser evaluate the container's size independently for container-query layout. Check your sizing rules if the wrapper unexpectedly collapses or changes available space.
Writing Your First `@container` Rule
Use @container to apply styles when the nearest eligible ancestor meets a condition.
@container (min-width: 25rem) {
.card {
grid-template-columns: 8rem 1fr;
}
}Below 25rem, the card remains a single-column grid. At or above that width, it gets two columns. The rule follows the component's placement, so the same component can work in multiple layouts.
Exercise
Why might a card use a poor layout even though the viewport is wide?
Show answer
Its local container may be narrow. A viewport query sees the wide browser window, while a container query sees the card's actual available space.