To use container queries, you need to declare a containment context on an element so that the browser knows you might want to query the dimensions of this container later. To do this, use the container-type
property with a value of size
, inline-size
, or normal
.
These values have the following effects:
size
-
The query will be based on the inline and block dimensions of the container. Applies layout, style, and size containment to the container.
inline-size
-
The query will be based on the inline dimensions of the container. Applies layout, style, and inline-size containment to the element.
normal
-
The element is not a query container for any container size queries, but remains a query container for container style queries.
Consider the following example of a card component for a blog post with a title and some text:
<div class="post">
<div class="card">
<h2>Card title</h2>
<p>Card content</p>
</div>
</div>
You can create a containment context using the container-type
property:
.post {
container-type: inline-size;
}
Next, use the @container
at-rule to define a container query. The query in the following example will apply styles to elements based on the size of the nearest ancestor with a containment context. Specifically, this query will apply a larger font size for the card title if the container is wider than 700px
:
.card h2 {
font-size: 1em;
}
@container (min-width: 700px) {
.card h2 {
font-size: 2em;
}
}
Using container queries, the card can be reused in multiple areas of a page without needing to know specifically where it will be placed each time. If the container with the card is narrower than 700px
, the font of the card title will be small, and if the card is in a container that's wider than 700px
, the font of the card title will be bigger.
For more information on the syntax of container queries, see the @container
page.