Given the following HTML example which is a card component with a title and some text:
<div class="card">
<div class="post-meta">
<h2>Card title</h2>
<p>My post details.</p>
</div>
<div class="post-excerpt">
<p>
A preview of my <a href="https://example.com">blog post</a> about cats.
</p>
</div>
</div>
To create a containment context, add the container-type
property to an element in CSS. The following example creates two containment contexts, one for the card meta information and one for the post excerpt:
Note: A shorthand syntax for these declarations are described in the container
page.
.post-meta {
container-type: inline-size;
}
.post-excerpt {
container-type: inline-size;
container-name: excerpt;
}
Writing a container query via the @container
at-rule will apply styles to the elements of the container when the query evaluates to true. The following example has two container queries, one that will apply only to the contents of the .post-excerpt
element and one that will apply to both the .post-meta
and .post-excerpt
contents:
@container excerpt (min-width: 400px) {
p {
visibility: hidden;
}
}
@container (min-width: 400px) {
p {
font-size: 2rem;
}
}
For more information on writing container queries, see the CSS Container Queries page.