Container Queries: Responsive Design Beyond the Viewport
What are Container Queries?
With container queries, you can query the styling information of a parent element, such as its inline-size
. With media queries, you could query the size of the viewport, container queries enable components that can change based on where they are in the UI.
Using container queries
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:
The query will be based on the inline and block dimensions of the container. Applies layout, style, and size containment to the container.
The query will be based on the inline dimensions of the container. Applies layout, style, and inline-size containment to the element.
The element is not a query container for any container size queries but remains a query container for container-style queries.
The @container
at-rule
The @container
at-rule allows you to style elements based on the size of their container. The container condition is evaluated when the container changes in size. Also, the @container at-rule is what primarily defines a container query. It takes this form:
@container <container-condition> {
<stylesheet>
}
Consider the following example of a card component for a blog post with a title and some text:
<div class="cardBlock">
<div class="cardDetails">
<h1>Card title</h1>
<p>Card content</p>
</div>
</div>
You can create a containment context using the container-type
property:
.cardBlock {
container-type: inline-size;
}
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
:
/* Default heading styles for the card title */
.cardBlock h1 {
font-size: 1em;
}
/* If the container is larger than 700px */
@container (min-width: 700px) {
.cardBlock h1 {
font-size: 2em;
}
}
a container query applied styles based on the nearest ancestor with a containment context. It’s possible to give a containment context a name using the container-name
property. Once named, the name can be used in a @container
query to target a specific container. The following example creates a containment context with the name sidebar
:
.cardBlock {
container-type: inline-size;
container-name: sidebar;
}
You can then target this containment context using the @container
at-rule:
@container sidebar (min-width: 700px) {
.cardDetails {
font-size: 2em;
}
}
Shorthand container syntax
The shorthand way of declaring a containment context is to use the container
property:
.post {
container: sidebar / inline-size;
}
Browser compatibility
Thanks for reading.