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.
- 01Write container size queriesMake an element a container with
container-type, ask about it with@container, name it, and size text withcqi. - 02Make the host a containerGive
:hosta block display and a container type, and know which containers a shadow root's rules can ask. - 03Let 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:
<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>- In the
tea-card.jstab, 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 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.
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
@mediaasks about - In real life: The table the tray is on
- In CSS: The container, which
@containerasks 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
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.
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:
<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>- 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:
<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>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.
- 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:
<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>- 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.
<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>- Line 2 makes
maina 400px container namedshop, 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.
<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>- 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:
<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>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.
- In the
tea-card.jstab, line 6 is the only line that changes: the card's:hostrule. 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.
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
@containerrule 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:
<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>- In the
tea-note.jstab, 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:
<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>- In the
tea-frame.jstab, line 7 makes an innerdiv.framea 200px container. Line 9 puts the slot inside it. - On the page, line 2 makes
.maina 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.
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:
<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>- Line 2 makes
maina 400px container namedlayout. Line 3 colors headings dim gray. Lines 4 to 6 color them sienna while thelayoutcontainer is at least 300px. - Line 10 puts a heading inside
tea-box. In thetea-box.jstab, line 6 names the box's 200px hostlayouttoo.
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.
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
layoutcontainer - In real life: The stall's back room, also called the kitchen
- In CSS: The box's host, named
layouttoo - 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:
<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>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.
- In the
tea-card.jstab, 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-layoutiscompact, 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.
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: compacton.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:
/* 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
.sidebarclass 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).
<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>- 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:
| Query | What it asks about | What it needs | Good 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?
@container (min-width: 320px) { .card { … } }, in a 400px card whose:hostisdisplay: block; container-type: inline-size- The same rule, but the
:hostrule is onlycontainer-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 { … } }
Sort each rule, in the setup it names.
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:
: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
.carda 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:
<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>- 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: compacton anything with the classquick. - 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.
--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:
<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>- 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:
<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>- Line 4 colors the notes dim gray. Lines 5 to 7 color them sea green while the container named
tea-cardis 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:
<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>- 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-typeon:hostis enough." No. A custom element is inline until CSS says otherwise, and an inline box is no container. Adddisplay: block. - "A container can change its own style from its own size." No. Rules inside
@containerstyle 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.
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>column, row, row. The 240px shelf is too narrow, so Green tea stays a column. Oolong's shelf is exactly 320px, and min-width: 320px includes it. Mint's 360px shelf is wider still.
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>Host border: rgb(105, 105, 105), dim gray. The host is the container, so it can't ask itself. The page's .main isn't a container, so line 8 never applies. Line 9, for the paragraph inside, does.
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><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>The page stays the same. In the tea-card.js tab, line 6 now gives the host display: block beside its container type. The host becomes a 400px container, so it prints Host: block and Layout: row.
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><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>The page stays the same. In the tea-card.js tab, lines 8 to 10 are the new style query. The sidebar's value inherits into its card's host, the query reads it there, and it prints sidebar column. The main card stays a row.
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><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>The page stays the same. In the tea-box.js tab, line 6 now names the host tea-box. The nearest layout container for the Green tea heading is main again, which is 400px. It prints Green tea rgb(160, 82, 45).
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>Layout: column. The shelf is 340px wide, padding included. A size query asks about the content box, the room inside the padding: 308px. That's less than 320px, so line 5 doesn't apply.
Check your understanding
For each question, ask: which container does the rule ask, and is the answer what the rule wants?
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.
Question 2 of 7A card's shadow root has
:host { container-type: inline-size; }and nothing else for the host. Why do its@containerrules never apply?Choose an answer to see the explanation.
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.
Question 4 of 7This note's host is a block, but not a container. What color does the page print?
Read the code, then predict<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.
Question 5 of 7A page names its main column
layout. A component it uses also names its hostlayout. What happens to the page's@container layout (…)rules for headings inside the component?Choose an answer to see the explanation.
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.
Question 7 of 7After the card became a container, a page that put cards in
display: flexrow 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-sizemakes a container you can ask about its width. Its width must come from outside, never from its content.- Rules inside
@containerstyle 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:
- CSS container queries, MDN.
- container-type, MDN.
- CSS Conditional Rules Level 5: container queries, W3C CSS Working Group.
- Styling Web Components: @layer and container queries inside components, Chrome for Developers, Modern Web Guidance.
- Container Queries in Web Components, Max Böck.
- CSS Container Queries flat tree lookup, Chrome Platform Status.
- Non-Tree-Scoped container-name Matching, Chrome Platform Status.
- Modern CSS Feature Support For Shadow DOM: Container Size Queries, Adobe Spectrum Web Engineering.
- Using container size and style queries, MDN.
- [css-scoping] :host-context(), issue 1914, W3C CSS Working Group on GitHub.
- Container style queries, web-features, on webstatus.dev.
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.