Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Container Queries, :has() Styling, Grid Subgrid, and Card Layout

How to size container queries, style parents with :has(), pick flex or grid, and build cards that adapt to their own space.

This page summarizes Chrome for Developers guidance on Modern Web Guidance, especially CSS Layouts and Responsive Design, Size Aware Styling, Child State Based Styling, Content Based Styling, and Build a Card. The goal is modular UI: components that respond to their width and their contents, not only the viewport.

Container queries vs media queries: when the component width matters

Section titled “Container queries vs media queries: when the component width matters”

People often look this up when a card or toolbar looks wrong in a sidebar but fine in the main column, or when @media breakpoints feel arbitrary for reusable components.

Query the size (or computed style) of an ancestor container rather than the viewport. Mental model: container queries = component context; media queries = global page layout and user preferences (prefers-color-scheme, prefers-reduced-motion).

— Chrome for Developers, CSS Layouts and Responsive Design

Responsive design points to the same split: use @container for component-driven layout; reserve viewport rules for page shell, motion, and color-scheme preferences. Styling Web Components adds that shadow-hosted components should use container queries on the host (with a real layout box such as display: block), not viewport media queries, so the same element works in narrow and wide regions.

Approach Best for Risk if misused
@media Page grid, global typography, prefers-* Component CSS tied to screen size, not slot width
@container (size) Cards, nav bars, tables in variable-width parents Missing container-type or unnamed nested containers
@container style() Themes, density, flags on custom properties Treating as Baseline-critical without fallback

container-type and @container: how to make a size container

Section titled “container-type and @container: how to make a size container”

Size-aware styling starts by marking which element is measured.

MANDATORY: You must first tell the browser which element is the container to be measured.

— Chrome for Developers, Size Aware Styling

Define inline-size containment on the wrapper

Section titled “Define inline-size containment on the wrapper”

On the wrapper (not necessarily every child):

.card-container {
container-type: inline-size;
}

For named queries when contexts nest, use the shorthand from CSS Layouts and Responsive Design:

.card-wrapper {
container: card / inline-size;
}

Write @container rules against the component

Section titled “Write @container rules against the component”

Default styles should be safe in narrow space (often a vertical stack). Widen layout only when the container crosses a threshold:

.card {
display: flex;
flex-direction: column;
gap: 1rem;
}
@container (min-width: 400px) {
.card {
flex-direction: row;
align-items: center;
}
}

Fluid Scaling recommends clamp() with container query units (cqi, cqb) so typography and padding scale with the wrapper, with viewport-based clamp() as fallback inside @supports (font-size: 1cqi).

:has() on the container: content-based and child state layout

Section titled “:has() on the container: content-based and child state layout”

Before :has(), teams added modifier classes in JavaScript or templates (.card--has-image, .is-active). Content Based Styling and Child State Based Styling require parent rules that detect descendants.

The :has() pseudo-class changes this, allowing you to conditionally style a container element depending on the presence or state of its descendants.

— Chrome for Developers, Child State Based Styling

MANDATORY: You must use the :has() selector on the container element to detect the presence of specific child content.

— Chrome for Developers, Content Based Styling

Match the Build a Card pattern: only apply side-by-side media layout when media exists—.card:has(> img) (or > picture, > video), not unconditional column grids that reserve an empty media track.

React to checked, focus, or validity without JS classes

Section titled “React to checked, focus, or validity without JS classes”

Override CSS variables on the container when a child enters a state:

.theme-card:has(.theme-toggle:checked) {
--card-bg: #222222;
--card-text: #f0f0f0;
}

CSS: Modern Architecture recommends :has() for parent styling instead of toggle classes, but warns: do not nest :has() or put pseudo-elements inside it. Scope :has() to the component root—not body:has(...)—to limit work during layout.

Flexbox, grid, and subgrid: which layout mode to pick

Section titled “Flexbox, grid, and subgrid: which layout mode to pick”

Use the decision flow from CSS Layouts and Responsive Design:

  1. One row or column of items → flexbox (flex-wrap: wrap when overflow is possible).
  2. Grandchildren must align to a parent grid’s tracks → subgrid.
  3. Rows and columns together → grid (repeat(auto-fit, minmax(...)) for responsive card grids).
  4. Component width drives layout → container-type on the card plus @container, not parent viewport breakpoints.

For aligned card rows (title, body, footer lining up across siblings), Build a Card and the layout guide recommend subgrid on four row tracks, with a same-cascade fallback grid-template-rows for browsers without subgrid.

Cross-axis habits from the layout guide: use gap not child margins; min-inline-size: 0 on flex items with long strings; avoid order or flex-direction: *-reverse on interactive content (focus order stays DOM order); avoid grid-auto-flow: dense on focusable grids for the same reason.

Section titled “Card markup, regions, and whole-card links”

Build a Card defines up to four direct child regions in source order: media, header (heading or hgroup/header), content (p/ul/dl or one wrapping div), footer (footer with distinct actions).

Base the layout on the card’s available space, not the viewport. To adapt the card’s descendants (media, text, actions), make the card the size container (container-type: inline-size) and write @container rules against its children.

— Chrome for Developers, Build a Card

For a primary destination plus other controls, put .card-link on one heading link and stretch hit area with ::after; raise other a, button, and inputs with position: relative; z-index: 1. Style hover/focus on .card:has(a.card-link:hover) so the ring reads as the card, not only the link.

Give informative images real alt text; use alt="" for decorative images. Use aspect-ratio and object-fit: cover on the media element itself to limit layout shift.

@container style(): density and themes without descendant coupling

Section titled “@container style(): density and themes without descendant coupling”

When the question is semantic context (featured section, compact density)—not width—see Design Token Reactivity, Semantic Component Adaptation, and Getting Started with Style Queries.

Container style queries allow authors to style elements based on the computed custom property value of an ancestor element.

— Chrome for Developers, Design Token Reactivity

Set a flag on an ancestor (--density: compact), then:

@container style(--density: compact) {
.card {
padding: 8px;
}
}

Style queries apply to descendants, not the element that owns the custom property (avoids loops). For non-core features, Chrome documents progressive enhancement with :where([data-density="compact"]) before style queries, or attribute fallbacks until Baseline coverage matches your target.

Selector & @-rule Combinations shows storing combined filters (e.g. resolved color scheme) on a custom property and branching with @container style(--color-scheme: dark) to avoid duplicating entire @media (prefers-color-scheme: dark) blocks.

For “select the hero image in the card, not every img,” Limit the reach of your selectors with the CSS @scope at-rule limits matching to a DOM subtree (donut scopes with to (...)), with scoping proximity winning at equal specificity—useful for nested .light / .dark regions.

CSS Nesting groups rules; use & for compounds like .card:has(a.card-link:focus-visible). Nesting does not concatenate BEM (&--header ≠ .card--header).

  • Viewport breakpoints on components placed in sidebars, dashboards, or shadow roots—use container-type: inline-size on the card or host.
  • @container without a qualifying ancestor—container units fall back toward small viewport sizes per the layout guide.
  • :has() on body for local UI—prefer .card:has(...) per performance guidance in the :has() guides.
  • Empty media column—scope multi-column card rules with :has(> img) (or equivalent media child).
  • Whole-card link on every footer link—only one .card-link per card.
  • Style queries as the only path for mandatory UI—Design Token Reactivity warns against that until support matches your Baseline.
  1. Open the page in Chrome, toggle Device Mode (layout guide references DevTools), and place the component in both a narrow and wide parent without changing viewport width—confirm layout follows the parent width.
  2. In DevTools, inspect the wrapper and verify computed container-type or container shorthand on the intended query root (Size Aware Styling).
  3. Temporarily add and remove optional children (image, checkbox toggle) and confirm layout/state changes come from :has() rules, not leftover modifier classes (Content Based Styling, Child State Based Styling).
  4. Tab through interactive cards and confirm focus order matches visible order (no order/dense grid surprises) per CSS Layouts and Responsive Design.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about, and we will correct or clarify it.