Sub topic 1
Why Components Should Respond to Their Container
Prerequisites
This chapter assumes solid CSS selectors and the cascade, media queries, viewport units, CSS custom properties, Flexbox or Grid, and clamp().
Why Components Should Respond to Their Container
A media query responds to the viewport. That works for page-level layout, but reusable components often appear in different contexts. A card might be wide in a main column and narrow in a sidebar, even though the viewport has not changed.
A container query lets a component respond to the size of an ancestor. The component can therefore choose a layout that fits its actual available space.
Declaring a Container with `container-type`
An element becomes a query container when you set container-type. The common value inline-size enables queries against the container’s inline size, which is usually its width in a horizontal writing mode.
The query applies to descendants of the container. It does not directly style the container itself.
Writing `@container` Size Queries
The following example keeps the card in a simple block layout until its wrapper is at least 30rem wide. The card then changes to a two-column Grid layout.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.card-wrapper {
container-type: inline-size;
max-width: 50rem;
resize: horizontal;
overflow: auto;
border: 1px solid #bbb;
padding: 1rem;
}
.card {
display: block;
}
@container (min-width: 30rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}
</style>
</head>
<body>
<div class="card-wrapper">
<article class="card">
<strong>Article</strong>
<p>This layout responds to the wrapper, not the viewport.</p>
</article>
</div>
</body>
</html>The @container condition checks the nearest eligible ancestor container. Unlike a media query, it does not inspect the browser window.
Exercise
Why might a card use a container query instead of a media query?
Show answer
A container query lets the card adapt to the width of the region that contains it, so the same component can work in both wide and narrow layouts.