DEV Community

Julia Shlykova
Julia Shlykova

Posted on

Container queries in css

Container queries are fully supported by the main browsers. They work similarly to media queries, with only a difference in what they are based on. Media queries depend on viewport size, while container ones depend on element size.

Table of contents

  1. Practical use of container queries
  2. Basic syntax
  3. Naming
  4. Container query length units
  5. Important notes

Practical use of container queries

Since container queries work similarly to media queries, in what cases would we prioritize container queries over media ones?

For example, when we have elements with the same style in different wrappers, where structure depends on the wrapper's size:

When item class element (in main and aside component) has enough width it splits into two columns.

Basic syntax

Let's learn with an example:

<div class="container">
 <div class="child">
  <h1>Title</h1>
  <p>lorem</p>
 </div>
</div>
Enter fullscreen mode Exit fullscreen mode

First, we need to set container-type property for our container, on the sizes of which we will use a query.

Values of container-type:

  • size - both dimensions;
  • inline-size - inline dimension;
  • normal - not for dimension changes but for container style queries (we can refer to container sizes inside the query).

For our example:

.container {
 container-type: inline-size;
}
Enter fullscreen mode Exit fullscreen mode

Next, we should use the css at-rule @container to define the query. It's set similar to media queries:

@container (width <= 400px) {
 .child {
  padding: 20px;
 }
}
Enter fullscreen mode Exit fullscreen mode

When the container width becomes no more than 400px, the child element's padding becomes 20px.

Naming

We can use container queries for several containers, and to distinguish them we can give names to the containers:

.container {
 container-type: inline-size;
 container-name: main;
}

@container main (width <= 400px) {
 .child {
  padding: 20px;
 }
}
Enter fullscreen mode Exit fullscreen mode

There is a shorthand property:

.container {
 container: main / inline-size;
}
Enter fullscreen mode Exit fullscreen mode

Container query length units

We can use special length units inside the container query:

  • cqw = 1% of the container's width;
  • cqh = 1% of the container's height;
  • cqi = 1% of the container's inline size;
  • cqb = 1% of the container's block size;
  • cqmin = min(cqi, cqb);
  • cqmax = max(cqi, cqb).

Important notes

  • We can change css attributes only for elements inside the container;
  • we can apply the same container-name to multiple containers;
  • container-type: size under the hood applies, besides layout and style, contain: size, which means that the container's size is computed as if it had no children. So, if you don't explicitly set the container sizes, the container will have zero height. See;
  • container queries may break subgrid.

Top comments (0)