completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Container queries in components

Learn container queries in web components: make the shadow host a container, query it from the shadow root, and let the page switch layouts with style queries.

By the end, you can
  • 01
    Write container size queriesMake an element a container with container-type, ask about it with @container, name it, and size text with cqi.
  • 02
    Make the host a containerGive :host a block display and a container type, and know which containers a shadow root's rules can ask.
  • 03
    Let the page switch the lookRead a custom property with a container style query, and keep a look that works where style queries don't.

What are container queries in web components?

Meena is laying out Leaf and Kettle's tea page. The main column is wide, and the sidebar is narrow. She puts the same tea card in both. In the main column, the card is one short line with empty space beside it. In the sidebar, the Add button is squeezed against the name.

She knows media queries. But both cards sit in the same window, so a media query gives them the same answer. How can one card know how much room it has?

A container query lets a component's CSS ask how wide its container is, instead of how wide the window is. In a web component, make the host a container with :host { display: block; container-type: inline-size; }, then write @container (min-width: 320px) { … } rules inside the shadow root. A container style query lets the page switch the look with a custom property.

Here is Meena's card in both places:

The same card in a wide column and a narrow sidebarPop out in the code editor (opens in a new tab)HTML
<style>  .main { width: 400px; }  .sidebar { width: 200px; }</style><div class="main"><tea-card></tea-card></div><div class="sidebar"><tea-card></tea-card></div> <script src="tea-card.js"></script><script>  for (const card of document.querySelectorAll("tea-card")) {    const box = card.shadowRoot.querySelector(".card");    console.log(card.parentElement.className, getComputedStyle(box).flexDirection);  }</script>
ResultLoading…
  • In the tea-card.js tab, line 6 makes the card's host a block and a container. Line 7 lays out the card as a column: the name, with the button under it.
  • Lines 8 to 10 of the tab are a container query. While the container is at least 320px wide, line 9 turns the card into a row.
  • On the page, lines 2 and 3 make a 400px main column and a 200px sidebar. Lines 5 and 6 put a card in each.
  • Lines 10 to 13 print where each card sits, and its flex-direction.

It prints main row and sidebar column. Same card, same window, two layouts. Each card asked its own container.

A window labelled page holds two smaller windows. The left one, .main, is wide; inside it, two cards side by side: Green tea and Add. Under it: 400px, a row. The right one, .sidebar, is narrow; inside it, the same two cards, one under the other. Under it: 200px, a column. At the bottom: each card asks its own column, not the window.page.mainGreen teaAdd400px: a row.sidebarGreen teaAdd200px: a columnEach card asks its own column, not the window
Both cards sit in one window, so a media query would give them one answer. Each card asks its own column instead: the 400px one gets a row, and the 200px one gets a column.

A container is an element that can answer questions about its size. A container query is a CSS rule that asks one. A media query asks the window. That suits the page's own layout. A component doesn't know where it will be used, so it asks about the room it was given. MDN calls container queries an alternative to media queries, which ask about the viewport.

Real-life analogyA tea tray that checks its table

A server at Leaf and Kettle carries a tray of four cups. On a long table, she sets them in a row. On a small side table, she puts them two by two. She never looks at how big the café is. She looks at the table she was given.

In real life: The size of the café
In CSS: The window, which @media asks about
In real life: The table the tray is on
In CSS: The container, which @container asks about
In real life: The tray of cups
In CSS: The component
In real life: Cups in a row, or two by two
In CSS: The rules inside @container
The main idea

A container query lets a component fit the room it gets. Make its host a block and a container. Write @container rules for what's inside the shadow root. Let the page flip a custom property, and read it with a style query.

How do container size queries work?

Lesson 12.4 put components on the page's grid. The page decides how wide each one is. A container size query lets what's inside react to that width. It takes two steps. Here they are on plain page elements first.

Step 1: make an element a container

The container-type property turns an element into a container. Two of its values are for size:

  • inline-size: rules can ask about its width. The inline size is the width, in a language written across the page, like English.
  • size: rules can ask about its width and its height.

A container gives something up in return. Its width can't come from what's inside it any more. MDN explains why: if a rule inside the query could change the container's size, the answer could flip back and forth forever. So the width comes from outside: from the container's parent, or from a width you set.

Real-life analogyA tea box in a shelf slot

Each shelf at the shop has slots. A tea box takes the width of its slot, not the width of the tins inside. So Ravi picks how to stand the tins by looking at the slot. Standing them a new way never makes the slot wider.

In real life: The shelf slot
In CSS: The width the page gives the container
In real life: The tea box
In CSS: The container
In real life: The tins inside
In CSS: The elements inside the container
In real life: Standing the tins to fit
In CSS: The rules inside @container

With size, the height can't come from the content either:

A size container with no height of its ownPop out in the code editor (opens in a new tab)HTML
<style>  .shelf { width: 200px; container-type: size; }  .shelf p { margin: 0; line-height: 24px; }</style><div class="shelf"><p>Green tea</p></div> <script>  const shelf = document.querySelector(".shelf");  console.log("Height:", shelf.getBoundingClientRect().height);</script>
ResultLoading…
  • Line 2 makes a 200px shelf a container of type size.
  • Line 3 makes the tea's line 24px tall. Line 9 prints the shelf's height.

It prints Height: 0. The shelf ignored the 24px line inside it. Press Edit & run and change size on line 2 to inline-size. It prints Height: 24. Most components only need their width, so inline-size is the usual choice.

Step 2: write an @container rule

An @container rule holds a condition and some rules. The rules apply while the condition is true. Change the shelf and watch:

Playground: how wide is the shelf?
A shelf that asks how wide it isPop out in the code editor (opens in a new tab)HTML
<style>  .shelf { width: 400px; container-type: inline-size; }  .tea { display: flex; flex-direction: column; gap: 8px; }  @container (min-width: 320px) {    .tea { flex-direction: row; }  }</style><div class="shelf">  <div class="tea"><strong>Green tea</strong><button>Add</button></div></div> <script>  const tea = document.querySelector(".tea");  console.log("Layout:", getComputedStyle(tea).flexDirection);</script>
ResultLoading…
Try it yourself
Wide enough

It prints Layout: row. The shelf is a container, 400px wide. That's at least 320px, so the rule on line 5 applies and the tea becomes a row: the name, then the button beside it.

Only line 2 changes: the shelf's width, and whether it's a container. A row puts the button beside the name; a column puts it under.
  • Line 2 is the only line that changes. In most choices, it makes the shelf a container.
  • Line 3 makes the tea a flex column: the name, with the button under it.
  • Lines 4 to 6 are the container query. (min-width: 320px) means 320px or wider. Line 5 applies only while that's true.
  • Line 14 prints the tea's flex-direction.

The query asks the nearest container around the element it styles. At 400px and 320px it prints Layout: row. At 200px it prints Layout: column. With no container-type, it's a column too: the query finds no container, so it never applies. You can also write the condition as (width >= 320px). And the width it asks about is the container's content box: the room inside its padding and border.

Can a container style itself?

No. Rules inside the query style what's inside the container:

A container that tries to restyle itselfPop out in the code editor (opens in a new tab)HTML
<style>  .shelf { width: 400px; container-type: inline-size; border: 2px solid dimgray; }  @container (min-width: 320px) {    .shelf { border-color: seagreen; }    .tea { color: seagreen; }  }</style><div class="shelf">  <p class="tea">Green tea</p></div> <script>  const shelf = document.querySelector(".shelf");  const tea = document.querySelector(".tea");  console.log("Shelf:", getComputedStyle(shelf).borderTopColor);  console.log("Tea:", getComputedStyle(tea).color);</script>
ResultLoading…
  • Line 2 makes a 400px shelf a container, with a dim gray border.
  • Line 4 tries to turn the shelf's own border sea green. Line 5 turns the tea sea green.
  • Lines 15 and 16 print both colors.

It prints Shelf: rgb(105, 105, 105) and Tea: rgb(46, 139, 87). The tea changed, and the shelf's border stayed dim gray. The spec picks the container from the element's ancestors. For the shelf, that means a container around the shelf, and there is none. Why it matters: put the rules that change on the elements inside a container, never on the container itself.

Naming a container

Containers can sit inside each other. A query with no name asks the nearest one. container-name gives a container a name, so a query can skip to it. The container shorthand sets both: the name, a slash, then the type.

An unnamed query and a named one, for the same paragraphPop out in the code editor (opens in a new tab)HTML
<style>  main { width: 400px; container: shop / inline-size; }  .note { width: 200px; container-type: inline-size; }  @container (min-width: 300px) { p { font-weight: bold; } }  @container shop (min-width: 300px) { p { color: seagreen; } }</style><main>  <div class="note"><p>Green tea</p></div></main> <script>  const p = getComputedStyle(document.querySelector("p"));  console.log("Bold:", p.fontWeight === "700");  console.log("Sea green:", p.color === "rgb(46, 139, 87)");</script>
ResultLoading…
  • Line 2 makes main a 400px container named shop, with the shorthand.
  • Line 3 makes the note a 200px container with no name.
  • Line 4 has no name, so it asks the nearest container, the note. Line 5 asks the container named shop.

It prints Bold: false and Sea green: true. The note is only 200px, so line 4 didn't apply. Line 5 skipped the note and asked main, which is 400px.

Container query units

Containers come with their own units. cqi is 1% of the container's inline size, and cqw is 1% of its width. In English text, they're the same.

A heading sized by its shelf's widthPop out in the code editor (opens in a new tab)HTML
<style>  .shelf { container-type: inline-size; }  .wide { width: 400px; }  .narrow { width: 200px; }  h3 { margin: 0; font-size: 6cqi; }</style><div class="shelf wide"><h3>Green tea</h3></div><div class="shelf narrow"><h3>Green tea</h3></div> <script>  for (const h3 of document.querySelectorAll("h3")) {    console.log(getComputedStyle(h3).fontSize);  }</script>
ResultLoading…
  • Line 2 makes both shelves containers. Lines 3 and 4 make one 400px wide and the other 200px.
  • Line 5 sizes every heading at 6cqi.

It prints 24px and 12px: 6% of 400, and 6% of 200. The heading follows its shelf with no query at all. Where no container is around, MDN says the units measure the small viewport instead.

How do you make a web component's host a container?

A component's best container is usually its own host: the custom element's tag. The page sizes the tag, and the shadow root's rules ask about it. Lesson 11.2 styled the host from inside with :host. It also showed that a custom element is display: inline until CSS says otherwise.

That display matters here. Chrome's styling guide says size containment doesn't apply to inline boxes, so :host needs a block display. Try four :host rules:

Playground: is the host a container?
One card in a 400px columnPop out in the code editor (opens in a new tab)HTML
<style>  .main { width: 400px; }</style><div class="main"><tea-card></tea-card></div> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  const box = card.shadowRoot.querySelector(".card");  console.log("Host:", getComputedStyle(card).display);  console.log("Layout:", getComputedStyle(box).flexDirection);</script>
ResultLoading…
Try it yourself
An inline host is no container

Line 6 of the tea-card.js tab is :host { container-type: inline-size; }. It prints Host: inline and Layout: column. A custom element is inline until CSS says otherwise. Size containment doesn't apply to an inline box, so container-type does nothing here. The query finds no container, and the card stays a column, though it has 400px.

Only line 6 of the tea-card.js tab changes: the card's :host rule. The card has 400px in every case.
  • In the tea-card.js tab, line 6 is the only line that changes: the card's :host rule. Lines 8 to 10 turn the card into a row from 320px.
  • On the page, line 2 gives the card a 400px column. Lines 10 and 11 print the host's display and the card's layout.

With no display, it prints Host: inline and Layout: column. The card has 400px, but no container to ask. Add display: block, and it's a row. display: contents takes away the host's box, and the container with it. A block with no container-type is no container either.

Real-life analogyA table has a width, a sentence doesn't

You can measure a table with a tape measure. A sentence in a book is harder. It runs to the end of one line and carries on in the next. Which width would you write down? An inline element is like the sentence. A block is like the table.

In real life: A sentence that wraps onto the next line
In CSS: An inline host
In real life: A table
In CSS: A host with display: block
In real life: A tape measure
In CSS: container-type: inline-size
In real life: Writing down the width
In CSS: The answer an @container rule gets

Line 8 of the tab doesn't name the host. It asks the nearest container around .card. In a shadow root, the first element around the top-level elements is the host, so that's the one it finds. Max Böck's bookstore demo uses a :host rule like this one, with a name added. Each book changes its look as it moves to a wider or narrower shelf.

Why it matters: write display: block and container-type together, in one :host rule. A page rule on the tag still beats :host, as lesson 11.4 showed. So a page that writes tea-card { display: inline; } turns the container off again.

Do container queries work across shadow DOM?

Yes, in both directions. Lesson 8.2 showed the flat tree: the tree the browser draws, with each shadow root inside its host and each slotted element inside its slot. Container queries look for containers along that tree, the spec says. Chrome, Firefox, and WebKit, Safari's engine, all do.

From the shadow root out to the page

A component doesn't have to be a container itself. Its rules can ask the page's containers:

A note that asks the page's containersPop out in the code editor (opens in a new tab)HTML
<style>  .main { width: 400px; container-type: inline-size; }  .sidebar { width: 200px; container: sidebar / inline-size; }</style><div class="main"><tea-note>Steep for 3 minutes.</tea-note></div><div class="sidebar"><tea-note>Steep for 3 minutes.</tea-note></div> <script src="tea-note.js"></script><script>  for (const note of document.querySelectorAll("tea-note")) {    const p = note.shadowRoot.querySelector("p");    console.log(note.parentElement.className, getComputedStyle(p).fontSize);  }</script>
ResultLoading…
  • In the tea-note.js tab, line 6 makes the host a block, but not a container. Line 7 sets 16px text.
  • Lines 8 to 10 of the tab shrink the text to 14px while the nearest container is 250px or narrower.
  • On the page, line 2 makes the main column a 400px container. Line 3 makes the sidebar a 200px container named sidebar.
  • Lines 10 to 13 print where each note sits, and its font size.

It prints main 16px and sidebar 14px. The query went out of the shadow root, through the host, to the page. A shadow root hides its insides from the page's selectors. It doesn't hide the page's containers from the component. Press Edit & run and change line 8 of the tab to @container sidebar (max-width: 250px) {. It prints the same: a name the page gave works inside the shadow root too.

From slotted content into the component

Content you slot into a component stays in the page's tree, but it's drawn inside the component. So its queries look up through the slot first:

The page's paragraph, slotted into a framePop out in the code editor (opens in a new tab)HTML
<style>  .main { width: 400px; container-type: inline-size; }  p { color: dimgray; }  @container (max-width: 250px) {    p { color: sienna; }  }</style><div class="main">  <tea-frame><p>Green tea</p></tea-frame></div> <script src="tea-frame.js"></script><script>  console.log(getComputedStyle(document.querySelector("p")).color);</script>
ResultLoading…
  • In the tea-frame.js tab, line 7 makes an inner div.frame a 200px container. Line 9 puts the slot inside it.
  • On the page, line 2 makes .main a 400px container. Line 3 colors paragraphs dim gray. Lines 4 to 6 color them sienna while the nearest container is 250px or narrower.
  • Line 9 puts the page's own paragraph inside tea-frame.

It prints rgb(160, 82, 45), sienna. In the page's HTML, the paragraph sits in .main, which is 400px. But it's drawn inside .frame, so the frame is its nearest container.

Two columns. Left, From a shadow root: a card <p> in its shadow root at the bottom, an arrow up to tea-note, the host, and an arrow up to .sidebar, a container. Under it: the host isn't a container, so the lookup goes on to the page. Right, From slotted content: a card <p> on the page at the bottom. An arrow goes up to <slot>, and another up to .frame, a container. Above it is a faded, crossed-out card, .main, 400px. Under it: the frame is nearer than .main.From a shadow root.sidebar, a containertea-note, the host<p> in its shadow rootThe host isn't a container,so the lookup goes on to the pageFrom slotted content.main, 400px.frame, a container<slot><p> on the pageThe frame is nearer than .main
A query asks the nearest container along the flat tree. From a shadow root, that path goes out through the host to the page. From slotted content, it goes up through the slot, so the frame inside the shadow root comes first.

Chrome moved to this flat tree lookup to match the spec and Firefox. Its feature entry says the old way skipped containers in the shadow trees content was slotted into, and that wasn't what authors expected. Why it matters: a page's rules for slotted content follow where that content is drawn.

When the page and a component use the same name

Container names aren't private to one tree. A name set in a shadow root works for the page's queries, and the other way round. Chrome's feature entry records that change, made to match the spec and Firefox. It's handy, and it's also how two names can clash:

The page and a component both name a container layoutPop out in the code editor (opens in a new tab)HTML
<style>  main { width: 400px; container: layout / inline-size; }  h3 { color: dimgray; }  @container layout (min-width: 300px) {    h3 { color: sienna; }  }</style><main>  <h3>Teas</h3>  <tea-box><h3>Green tea</h3></tea-box></main> <script src="tea-box.js"></script><script>  for (const h3 of document.querySelectorAll("h3")) {    console.log(h3.textContent, getComputedStyle(h3).color);  }</script>
ResultLoading…
  • Line 2 makes main a 400px container named layout. Line 3 colors headings dim gray. Lines 4 to 6 color them sienna while the layout container is at least 300px.
  • Line 10 puts a heading inside tea-box. In the tea-box.js tab, line 6 names the box's 200px host layout too.

It prints Teas rgb(160, 82, 45) and Green tea rgb(105, 105, 105). For the Green tea heading, the nearest container called layout is the box, not main. The box is only 200px, so that heading stayed dim gray.

Real-life analogyTwo rooms called the kitchen

Leaf and Kettle's café has a kitchen. A tea stall inside the café calls its back room the kitchen too. A runner at the stall is told to take a tray to the kitchen, and goes to the nearest one: the stall's. A fuller name sends him to the right room.

In real life: The café's kitchen
In CSS: The page's layout container
In real life: The stall's back room, also called the kitchen
In CSS: The box's host, named layout too
In real life: A runner told to go to the kitchen
In CSS: A query for layout
In real life: A fuller name, the tea stall's kitchen
In CSS: A name that starts with the tag, tea-box

Name a component's containers after its tag, the way lesson 12.1 named its custom properties: tea-box, or tea-box-frame for one inside. Exercise 5 makes that fix. Adobe's shadow DOM tracker rates container size queries across the boundary as acceptable support: the common cases work everywhere, and Safari still fails some of the web platform tests.

What are container style queries?

A size query asks how big a container is. A style query asks what value a custom property has. The page sets a value, and the component reads it. MDN notes that every element can answer a style query, so no container-type is needed. Move the value around:

Playground: where does the page set it?
Two cards, and one value the page setsPop out in the code editor (opens in a new tab)HTML
<style>  .sidebar { --tea-card-layout: compact; }</style><div class="main"><tea-card></tea-card></div><div class="sidebar"><tea-card></tea-card></div> <script src="tea-card.js"></script><script>  for (const card of document.querySelectorAll("tea-card")) {    const box = card.shadowRoot.querySelector(".card");    console.log(card.parentElement.className, getComputedStyle(box).flexDirection);  }</script>
ResultLoading…
Try it yourself
Set on the sidebar

It prints main row and sidebar column. The value is set on .sidebar and inherits down into the card's host. The style query on line 8 of the tab reads it there, so only the sidebar's card turns into a column.

Only line 2 changes: where the page sets --tea-card-layout, and to what. The card's style query is on line 8 of the tea-card.js tab.
  • In the tea-card.js tab, line 6 gives the host a display, and no container type. Line 7 lays out the card as a row.
  • Lines 8 to 10 of the tab are the style query. While --tea-card-layout is compact, line 9 makes the card a column, with less padding.
  • On the page, line 2 is the only line that changes. Lines 9 to 12 print where each card sits, and its layout.

With the value on .sidebar, it prints main row and sidebar column. Custom properties cross the shadow boundary, as lesson 12.1 showed. The value inherits into the host, and the query asks the host about it. The value must match: small leaves both cards rows.

Three cards, one above the other. The top: .sidebar { --tea-card-layout: compact; }. An arrow down, labelled inherits, to the second: tea-card, the host: compact. An arrow down, labelled style() asks the host, to the third: .card: flex-direction: column. At the bottom: no container-type needed, every element answers a style query..sidebar { --tea-card-layout: compact; }inheritstea-card, the host: compactstyle() asks the host.card: flex-direction: columnNo container-type needed: every element answers a style query
The page sets the value once, on the sidebar. It inherits into the card's host, like any custom property. The card's style query reads it on the host and turns the card into a column.
Real-life analogyA note on the table

The manager puts a note on a corner table: Small plates only. The server reads it and brings small plates. The manager never touches a plate, and the server doesn't need to know why the table is small.

In real life: The manager
In CSS: The page
In real life: The note, Small plates only
In CSS: --tea-card-layout: compact on .sidebar
In real life: The server reading the note
In CSS: @container style(--tea-card-layout: compact)
In real life: Bringing small plates
In CSS: The compact look

A replacement for :host-context()

Lesson 11.2 met :host-context(), which checks the classes around the host. Only Chrome ships it. When the CSS Working Group decided to drop it, the discussion noted that style queries can replace most of its uses. The page sets a custom property, and the shadow tree uses a style query:

A :host-context() rule and the style query that replaces itCSS
/* Lesson 11.2's way: the card looks for a class around it */
:host-context(.sidebar) .card { flex-direction: column; }

/* A style query: the page sets a value, and the card reads it */
@container style(--tea-card-layout: compact) {
  .card { flex-direction: column; }
}
  • Line 2 looks for a .sidebar class anywhere around the host. It works only in Chrome.
  • Lines 5 to 7 read a value the page chose to set. The component doesn't care which element set it, or why.

Which browsers support container style queries?

Chrome, Firefox, and Safari all support style queries for custom properties. They're Baseline newly available: Firefox was the last of the three to add them. Size queries are Baseline widely available.

There's no @supports test for a style query. You rarely need one. A browser that can't read a condition skips the whole block, so put the everyday look outside it. Chrome can show you: MDN says no browser supports style queries for ordinary properties yet, like style(font-weight: bold).

A condition Chrome can't read yetPop out in the code editor (opens in a new tab)HTML
<style>  .tea { color: dimgray; }  @container style(font-weight: bold) {    .tea { color: seagreen; }  }</style><div style="font-weight: bold">  <p class="tea">Green tea</p></div> <script>  console.log(getComputedStyle(document.querySelector(".tea")).color);</script>
ResultLoading…
  • Line 2 is the everyday look: dim gray.
  • Line 3 asks about an ordinary property. Line 7 makes the element around the tea bold, so the answer would be yes.

It prints rgb(105, 105, 105). Chrome skipped the block, and line 2's look stayed. A browser without style queries does the same with style(--tea-card-layout: compact): the card keeps its everyday look. If the compact look must work in every browser, give the component an attribute as well, matched with :host([layout="compact"]), as lesson 11.2 did.

Here are the three kinds of query side by side. Read each row across:

Media queries, container size queries, and container style queries
QueryWhat it asks aboutWhat it needsGood for
@media (min-width: 320px)The window, the same for every element on the page.Nothing.The page's own layout: how many columns it has.
@container (min-width: 320px)The nearest container around the element.An ancestor with container-type, and a box: a block, not inline.A component that fits the room it gets.
@container style(--tea-card-layout: compact)A custom property's value on the nearest element around it.Nothing. Every element can answer a style query.A switch the page can flip, like a compact look.

Building a responsive tea card

Before the kit changes, sort these rules. Does each one ever apply?

Does the rule apply?
  • @container (min-width: 320px) { .card { … } }, in a 400px card whose :host is display: block; container-type: inline-size
  • The same rule, but the :host rule is only container-type: inline-size
  • @container (min-width: 320px) { :host { … } }, with the host as the container
  • @container style(--tea-card-layout: compact) { .card { … } }, in a card inside .sidebar { --tea-card-layout: compact; }
  • The same style query, but the sidebar sets --tea-card-layout: small
  • @container sidebar (max-width: 250px) { .card { … } }, in a card inside the page's 200px .sidebar { container: sidebar / inline-size; }
  • @container style(display: block) { .card { … } }
Try it yourself
0 of 7 correct

Sort each rule, in the setup it names.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Now the kit's tea-card lays itself out by its own width, and the page can force a compact look. Its markup gets one wrapper, div.info, around the name, the price, and the notes. Here is its style sheet now:

The style sheet in tea-kit/tea-card.jsCSS
:host {
  display: block;
  container: tea-card / inline-size;
  --_bg: var(--tea-card-bg, white);
  --_accent: var(--tea-card-accent, seagreen);
  --_radius: var(--tea-radius, 8px);
}
.card { display: flex; flex-direction: column; border: 2px solid var(--_accent); border-radius: var(--_radius); padding: 8px 12px; background: var(--_bg); }
h3 { margin: 0; color: var(--_accent); font-family: var(--tea-font-display, Georgia, serif); }
p { margin: 4px 0 0; }
h4 { margin: 8px 0 0; }
:host(:not(:state(has-notes))) #notes { display: none; }
.buy { display: flex; align-items: center; gap: 8px; margin-top: 8px; }
button { font: inherit; }
::slotted(p) { margin: 4px 0 0; }
@container (min-width: 320px) {
  .card { flex-direction: row; align-items: center; gap: 12px; }
  .info { flex: 1; }
  .buy { margin-top: 0; }
}
@container style(--tea-card-layout: compact) {
  .card { flex-direction: column; align-items: stretch; gap: 0; padding: 4px 8px; }
  .buy { margin-top: 4px; }
}
  • Line 2 gives the host a block display. Line 3 makes it a container named tea-card, after its tag.
  • Lines 4 to 6 are lesson 12.1's private --_ names, as before.
  • Line 8 makes .card a flex column: the stacked look the card always had.
  • Lines 16 to 20 are the size query. From 320px, line 17 makes the card a row, and line 18 lets the info take the spare room.
  • Lines 21 to 24 are the style query. Line 22 keeps the card a column with tighter padding, at any width. It comes last, so it wins.

The new name follows lesson 12.1's pattern: the kit, then the component, then its job. The card's JSDoc documents it with the @cssprop tag, as lesson 12.1 showed, and the manifest lists it. It has no default: unset, the card picks its layout by its width. Now one page uses it three ways:

The kit's card in a wide column, forced compact, and in a sidebarPop out in the code editor (opens in a new tab)HTML
<style>  .shop { display: grid; grid-template-columns: 360px 180px; gap: 16px; align-items: start; }  main { display: grid; gap: 8px; }  .quick { --tea-card-layout: compact; }</style><div class="shop">  <main>    <tea-card name="Green tea" price="4"></tea-card>    <tea-card class="quick" name="Mint" price="3"></tea-card>  </main>  <aside>    <tea-card name="Oolong" price="5"></tea-card>  </aside></div> <script type="module">  import "./tea-kit/index.js";  for (const card of document.querySelectorAll("tea-card")) {    const box = card.shadowRoot.querySelector(".card");    console.log(card.getAttribute("name"), card.getBoundingClientRect().width, getComputedStyle(box).flexDirection);  }</script>
ResultLoading…
  • Line 2 is the shop's grid: a 360px main column and a 180px sidebar, 16px apart.
  • Line 3 stacks the main column's cards. Line 4 sets --tea-card-layout: compact on anything with the class quick.
  • Line 9 gives Mint that class. Line 20 prints each card's name, width, and layout.

It prints Green tea 360 row, Mint 360 column, and Oolong 180 column. Green tea and Mint have the same room, and the page made Mint compact with one custom property. Oolong is a column because its sidebar is narrow. The page never had to know how the card lays itself out.

Three windows. The first, 180px, holds two cards one under the other: Green tea, and - 1 + Add 1. Under it: under 320px, a column. The second, 360px, holds the same two cards side by side. Under it: 320px and up, a row. The third, compact, holds the two cards one under the other again. Under it: compact, a column at any width.180pxGreen tea- 1 + Add 1under 320px: a column360pxGreen tea- 1 + Add 1320px and up: a rowcompactGreen tea- 1 + Add 1compact: a column at any width
One card, three looks. Its own width picks between a column and a row. --tea-card-layout: compact keeps it a column, however wide it is.

Dragging the card's width

Now change the room yourself. Drag the slider in the result:

A card in a box you can resizePop out in the code editor (opens in a new tab)HTML
<label>Width <input type="range" min="160" max="480" step="40" value="360"></label><output></output><div class="box" style="width: 360px">  <tea-card name="Green tea" price="4"></tea-card></div> <script type="module">  import "./tea-kit/index.js";  const input = document.querySelector("input");  const box = document.querySelector(".box");  const card = document.querySelector("tea-card").shadowRoot.querySelector(".card");  function show() {    box.style.width = `${input.value}px`;    document.querySelector("output").textContent = `${input.value}px: ${getComputedStyle(card).flexDirection}`;  }  input.addEventListener("input", show);  show();</script>
ResultLoading…
  • Line 1 is the slider: 160px to 480px, in steps of 40.
  • Line 13 sets the box's width. Line 14 writes the width and the card's flex-direction into the output on line 2.

At 280px it shows 280px: column. At 320px it turns into a row. Press Edit & run and add style="--tea-card-layout: compact" to the card on line 4. Now it's a column at every width.

Styling the notes by the card's width

The page can ask about a card by name. Because the kit named its container after its tag, the name can't clash:

The page's notes, styled by the card's widthPop out in the code editor (opens in a new tab)HTML
<style>  .narrow { width: 200px; }  .wide { width: 400px; }  tea-card p { color: dimgray; }  @container tea-card (min-width: 320px) {    tea-card p { color: seagreen; }  }</style><div class="narrow"><tea-card name="Mint" price="3"><p>Fresh and cool.</p></tea-card></div><div class="wide"><tea-card name="Green tea" price="4"><p>Grassy and light.</p></tea-card></div> <script type="module">  import "./tea-kit/index.js";  for (const p of document.querySelectorAll("tea-card p")) {    console.log(p.textContent, getComputedStyle(p).color);  }</script>
ResultLoading…
  • Line 4 colors the notes dim gray. Lines 5 to 7 color them sea green while the container named tea-card is at least 320px.
  • Lines 9 and 10 put a card in a 200px box and another in a 400px box, each with a note.

It prints Fresh and cool. rgb(105, 105, 105) and Grassy and light. rgb(46, 139, 87). The notes are the page's own paragraphs. The page found each card's container by its name, though the card set that name inside its shadow root.

Give a container a width

One thing to watch. A container's width can't come from its content, as step 1 said. So where nothing gives it a width, it has none:

Two cards in a flex rowPop out in the code editor (opens in a new tab)HTML
<style>  .row { display: flex; gap: 8px; }</style><div class="row">  <tea-card name="Green tea" price="4"></tea-card>  <tea-card name="Oolong" price="5" style="flex: 1"></tea-card></div> <script type="module">  import "./tea-kit/index.js";  for (const card of document.querySelectorAll("tea-card")) {    console.log(card.getAttribute("name"), card.getBoundingClientRect().width > 0);  }</script>
ResultLoading…
  • Line 2 makes a flex row. Line 5 is a card with no width.
  • Line 6 has flex: 1, so it takes the row's spare room. Line 12 prints whether each card has any width.

It prints Green tea false and Oolong true. The first card shrank to nothing. Give a container a width, a grid column, or flex: 1. A block in normal flow takes its parent's width, and a grid column like lesson 12.4's shelf gives it one too.

Common mix-ups

  • "A container query asks about the window." No. That's a media query. A container query asks the nearest container around the element.
  • "container-type on :host is enough." No. A custom element is inline until CSS says otherwise, and an inline box is no container. Add display: block.
  • "A container can change its own style from its own size." No. Rules inside @container style what's inside the container. The container asks someone further out.
  • "A container grows to fit its content." No. Its width comes from outside. In a flex row with no width, it shrinks to nothing. With size, its height does too.
  • "Shadow DOM hides the page's containers from a component." No. The lookup goes out through the host to the page, and slotted content looks up through its slot.
  • "Container names are private to a component." No. The page and every component share them. Start each name with the tag.
  • "Style queries can test any property, like display." No. Browsers support them for custom properties only. A condition a browser can't read never matches.
  • "A style query needs container-type." No. Every element can answer a style query.

Practice exercises

Answer first, then use the hints. The pages run live, so you can check yourself.

Exercise 1 · Warm-upPredict three shelves

Three shelves are containers, 240px, 320px, and 360px wide. What does the page print?

<style>  .shelf { container-type: inline-size; }  .tea { display: flex; flex-direction: column; }  @container (min-width: 320px) {    .tea { flex-direction: row; }  }</style><div class="shelf" style="width: 240px"><div class="tea">Green tea</div></div><div class="shelf" style="width: 320px"><div class="tea">Oolong</div></div><div class="shelf" style="width: 360px"><div class="tea">Mint</div></div> <script>  const layouts = [...document.querySelectorAll(".tea")].map((tea) => getComputedStyle(tea).flexDirection);  console.log(layouts.join(", "));</script>
ResultLoading…

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upCan the card restyle its own host?

    The card is a 400px container. Its own query tries to turn its host's border sea green. What does the page print?

    <style>  .main { width: 400px; }</style><div class="main"><tea-card></tea-card></div> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  console.log("Host border:", getComputedStyle(card).borderTopColor);</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeMake the host a container

      The card has 400px, but it prints Layout: column. Fix line 6 of the tea-card.js tab. What does the Layout line print then?

      <style>  .main { width: 400px; }</style><div class="main"><tea-card></tea-card></div> <script src="tea-card.js"></script><script>  const card = document.querySelector("tea-card");  const box = card.shadowRoot.querySelector(".card");  console.log("Host:", getComputedStyle(card).display);  console.log("Layout:", getComputedStyle(box).flexDirection);</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeAdd the compact switch

        The page asks for a compact card in the sidebar, but both print row. Change the tea-card.js tab, not the page. What does the sidebar's line print then?

        <style>  .sidebar { --tea-card-layout: compact; }</style><div class="main"><tea-card></tea-card></div><div class="sidebar"><tea-card></tea-card></div> <script src="tea-card.js"></script><script>  for (const card of document.querySelectorAll("tea-card")) {    const box = card.shadowRoot.querySelector(".card");    console.log(card.parentElement.className, getComputedStyle(box).flexDirection);  }</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeFix a name clash

          The page wants every heading sienna. The one inside tea-box stays dim gray. Rename the box's container in its tab. What does the Green tea line print then?

          <style>  main { width: 400px; container: layout / inline-size; }  h3 { color: dimgray; }  @container layout (min-width: 300px) {    h3 { color: sienna; }  }</style><main>  <h3>Teas</h3>  <tea-box><h3>Green tea</h3></tea-box></main> <script src="tea-box.js"></script><script>  for (const h3 of document.querySelectorAll("h3")) {    console.log(h3.textContent, getComputedStyle(h3).color);  }</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengePredict a shelf with padding

            The shelf is 340px wide, with 16px of padding on each side. The query asks for 320px. What does the page print?

            <style>  .shelf { box-sizing: border-box; width: 340px; padding: 16px; container-type: inline-size; }  .tea { display: flex; flex-direction: column; }  @container (min-width: 320px) {    .tea { flex-direction: row; }  }</style><div class="shelf"><div class="tea"><strong>Green tea</strong><button>Add</button></div></div> <script>  const tea = document.querySelector(".tea");  console.log("Layout:", getComputedStyle(tea).flexDirection);</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask: which container does the rule ask, and is the answer what the rule wants?

              The container queries quiz · 7 questionsScore: first tries count
              1. Question 1 of 7A tea card sits in a 200px sidebar, in a window 1200px wide. Which rule inside the card can tell it's narrow?

                Choose an answer to see the explanation.

              2. Question 2 of 7A card's shadow root has :host { container-type: inline-size; } and nothing else for the host. Why do its @container rules never apply?

                Choose an answer to see the explanation.

              3. Question 3 of 7Inside a shadow root, the host is a 400px container. Which of these does @container (min-width: 320px) { … } style?

                Choose an answer to see the explanation.

              4. Question 4 of 7This note's host is a block, but not a container. What color does the page print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <style>
                  .sidebar { width: 200px; container-type: inline-size; }
                </style>
                <div class="sidebar"><tea-note></tea-note></div>
                
                <script>
                  customElements.define("tea-note", class extends HTMLElement {
                    constructor() {
                      super();
                      this.attachShadow({ mode: "open" }).innerHTML = `<style>
                        :host { display: block; }
                        p { color: dimgray; }
                        @container (max-width: 250px) { p { color: seagreen; } }
                      </style><p>Steep for 3 minutes.</p>`;
                    }
                  });
                  const p = document.querySelector("tea-note").shadowRoot.querySelector("p");
                  console.log(getComputedStyle(p).color);
                </script>

                Choose an answer to see the explanation.

              5. Question 5 of 7A page names its main column layout. A component it uses also names its host layout. What happens to the page's @container layout (…) rules for headings inside the component?

                Choose an answer to see the explanation.

              6. Question 6 of 7A browser supports container size queries but not style queries. What does it do with @container style(--tea-card-layout: compact) { … }?

                Choose an answer to see the explanation.

              7. Question 7 of 7After the card became a container, a page that put cards in display: flex row with no width saw one shrink to nothing. Why?

                Choose an answer to see the explanation.

              Key takeaways

              • A container query asks the nearest container around an element, not the window. A component uses it to fit the room it gets.
              • container-type: inline-size makes a container you can ask about its width. Its width must come from outside, never from its content.
              • Rules inside @container style what's inside the container, never the container itself.
              • For a web component, write :host { display: block; container-type: inline-size; }. An inline host is no container.
              • Queries follow the flat tree: from a shadow root out to the page, and from slotted content up through its slot.
              • Container names are shared by the page and every component. Start each one with the tag, like tea-card.
              • @container style(--tea-card-layout: compact) reads a value the page sets. Keep the everyday look outside it, for browsers that can't read it.

              Remember the one-liner.
              A component asks its table, never the café. Make the host a block container, name it after its tag, and read the page's note with a style query.

              Sources

              The facts on this page come from these standards, docs, and posts:

              Coming next: Organizing component CSS. A library's tokens, base styles, and per-component rules each get a place, so the whole kit stays easy to change.

              CompleteFrontend Clear concepts. Working examples.