Container Queries in CSS

Almost as soon as media queries landed in browsers, developers began asking for a way to change the layout of components based on the width of their container, instead of the browser viewport. A few developers have used JavaScript to create responsive containers and element queries that have a similar effect, but browser implementations have never gone beyond the specification phase.

In March of 2021, however, Chrome announced some movement in this space. Google released Chrome Canary with an experimental container queries implementation, based on a draft specification for single-axis containment.

Work on the container queries feature is now part of the CSS Containment specification . We may soon be able to create adaptable layouts using an @container rule with a syntax that’s similar to @media :

.simple-input {

contain: layout inline-size; /* Creates a containment context for the inline axis */

}

.simple-input input,

.simple-input button {

display: block;

font: inherit;

padding: 2px;

}

@container (min-width: 40rem) {

.simple-input {

display: flex;

gap: 1rem;

}

}

To experiment with container queries today, install Chrome or Chromium. Enable the feature by typing chrome://fLags/#enabLe-container-queries in the address bar, and selecting Enabled from the Enable CSS Container Queries menu.

Both David A. Herron’s “Container Queries: a Quick Start Guide and the Mozilla Developer Network’s “CSS Container Queries” are fantastic introductions to container queries.

CodePen also has a growing collection of container query demos worth exploring . If poring over technical details is your thing, read Miriam Suzanne’s “Container Query Proposal & Explainer” .

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *