Container queries
Learning objectives
- You know what container queries are and what they are used for.
One of the more recent additions to CSS is container queries, which allow defining styles based on the size of the container. This is in contrast to media queries, which are used to define styles based on the size of the viewport.
Note: Container queries are still not supported by all browsers. In September 2023, based on caniuse data, approximately 86% of all internet users have browsers that support container queries.
Container queries are useful as they provide more control over the styling in relation to a container. Container queries are used with the @container
tag, which is used in the same way as the @media
tag. However, containers need to also be declared a containment context, which is used to define the container that the container query relates to (e.g. the container whose size is being adjusted to).
The following example defines a container that has a different layout depending on the size of the container. The container is defined as a grid, with three columns if the width of the container is larger than 640px, and two columns if the width of the container is smaller than 640px. Furthermore, the container is set to be a containment context (container-type: inline-size
) -- that is, all container queries are related to the element with the id container
.
In addition, the example also defines a class .item
that is used to style the items in the container. By default, the items have a margin of 0.75em and a padding of 0.75em, and the items have a light green background color. However, if the width of the container (not the item) is larger than 800px, the margin and padding are increased to 1em, and the color changes to light blue.
#container {
container-type: inline-size;
}
@media (max-width: 639px) {
#container {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
@media (min-width: 640px) {
#container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
}
.item {
border-radius: 0.33em;
background-color: rgb(207, 232, 220);
margin: 0.75em;
padding: 0.75em;
}
@container (min-width: 800px) {
.item {
margin: 1em;
padding: 1em;
background-color: lightblue;
}
}
The above styling would behave as follows (note that the styling might not be applied, depending on whether your browser supports container queries).