10 Container queries

 

This chapter covers

  • Defining containers and using the @container at-rule
  • Making modules responsive based on their container’s size
  • Using container-relative units
  • Using style queries to change styles based on the values of custom properties

We’ve now looked at organizing CSS into easy-to-reuse modules. This sort of approach makes it possible for large teams to use the same CSS when building large-scale websites and web applications. However, designing a module that can be used anywhere on the page can be difficult in the context of responsive design. You will often find you want to place a module in a narrow column, such as a sidebar. While the viewport itself may be large, the space available for that particular module is not. So a regular @media query is not always a practical approach for making the module responsive.

A new feature of CSS, container queries, provides a more versatile option. There are two types of container queries: container size queries and container style queries. Container size queries allow you to modify the styles of elements on the page based on the width of their container element. Container style queries allow you to modify styles based on a custom property of the container.

10.1 A basic example of a container query

10.1.1 Using container size queries

10.2 A closer look at containers

10.2.1 Container types

10.2.2 Container names

10.2.3 Containers and modular CSS

10.3 Container-relative units

10.4 Container style queries

10.4.1 Decoupling a module from its container

10.4.2 Reducing code duplication

Summary