2 min read

CSS Container Queries

Container Queries allow you to style elements based on the size of their container rather than the size of the viewport. This is a major shift from Media Queries and enables truly modular, responsive components.

1. The Concept

With Media Queries (@media), a card component might look one way on mobile and another on desktop. But what if that card is placed in a narrow sidebar on a desktop screen? Media queries sees "desktop width" and styles it wide, breaking the layout.

Container Queries (@container) solve this. The card asks "How much space do I have?" and adapts accordingly, regardless of where it is on the page.

2. Defining a Container

To use container queries, you must first define a containment context on a parent element.

.card-container {
  container-type: inline-size;
  container-name: card; /* Optional */
}
  • container-type:
    • size: Queries based on inline and block dimensions.
    • inline-size: Queries based on inline dimensions (width in horizontal writing modes). This is the most common.
    • normal: The element is not a query container (default).

3. Querying the Container

Now, the child elements can query their container.

.card {
  display: flex;
  flex-direction: column;
}

@container (min-width: 400px) {
  .card {
    flex-direction: row; /* Switch to row if container is wide enough */
  }
}

4. Named Containers

If you have nested containers, you can specify which one you want to query using container-name.

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

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

@container sidebar (min-width: 300px) {
  /* Styles for elements inside sidebar */
}

5. Container Query Units

Container queries introduce new units relative to the container's size.

  • cqw: 1% of a query container's width.
  • cqh: 1% of a query container's height.
  • cqi: 1% of a query container's inline size.
  • cqb: 1% of a query container's block size.
  • cqmin: The smaller value of cqi or cqb.
  • cqmax: The larger value of cqi or cqb.
h2 {
  font-size: 5cqi; /* 5% of the container's inline size */
}

programming/css/css programming/css/responsive-design programming/css/units