A Second Route to Container Queries

David Baron, a Principal Engineer at Firefox, has published a public proposal on how container queries might actually be implemented. The idea arrives as a second possible direction, following the positive February 2020 signals around a switch-statement syntax that would expose an available-inline-size for conditionally setting individual values.

Demand for container queries is near-universal among designers and developers, and browser vendors are aware of it. The sticking point has never been interest but complexity. Baron's proposal adds another option that sits within the realm of the possible rather than settling the question.

The @rule Form

Where the earlier approach revolved around a switch statement, this one is built on an at-rule. The document describes it as follows:

@container <selector> (<container-media-query>)? {
  // ... rules ...
}

In practice, a query written this way would look something like:

.parent {
  contain: layout inline-size;
  display: grid;
  grid-template-columns: 100%;
  gap: 1rem;
}
@container .parent (min-width: 400px) {
  grid-template-columns: 1fr 1fr;

  .child::before {
     content: "Hello from container query land!";
   }
}

Open Questions

Two details remain unresolved at this stage.

  • It is unclear whether the selector would need to be repeated inside the rule, or whether property/value pairs placed there would automatically apply to the selector named in the @rule.
  • Baron notes that "The rules can match only that container's descendants. Probably we'd need support for some properties applying to the container itself, but others definitely can't." Whether grid properties would qualify as changeable is an open question. Without that, authors would likely work around the descendant-only limit by wrapping elements in something like <div class="container-query">.

Containment as a Prerequisite

Containment appears central to making any of this work: if an element is not property contained, the container query simply will not function. Rachel Andrew's deep dive on the contain property from late last year covers the underlying mechanics.

This remains super early days, and no one can say with confidence which of these ideas will reach browsers.