Container queries is a relatively new addition for responsive design in CSS as an alternative to @media queries. 1 It allow us to style an element with regard to its parent or container size.

container queries.jpg

Motivation

Media queries are based on “when the browser’s viewport exceeds certain width and height”. However, if a component doesn’t match the width of the viewport, container queries can often be a better choice. 2

Examples where a container queries can be useful including card components, pagination, and sidebars that may become full-width on mobile but only occupy a small part on wide screen. 3

How it Works

We can have something like the following 4:

.parent {
  container: layout inline-size;
}
 
@container (min-width: 400px) {
  .child {
    display: flex;
    flex-wrap: wrap;
  }
}

container: layout inline-size tells the parent that a child needs to change size. The container property is a shorthand for container-name and container-type.

See also

Footnotes

  1. CSS container queries - CSS: Cascading Style Sheets | MDN

  2. On container queries. — Ethan Marcotte

  3. Say Hello To CSS Container Queries

  4. Say Hello to CSS Container Queries | CSS-Tricks