Custom states and :state()
Learn how custom states let a web component expose states like ready or checked, how CSS :state() styles them, and when a state beats an attribute.
- 01Turn states on and offAsk for
ElementInternalsin the class, then add and delete names withstates.add()andstates.delete(). - 02Style states from inside and outsideMatch a state with
:host(:state(ready)),tea-kettle:state(ready), andtea-kettle:state(ready)::part(spout). - 03Choose a state or an attributeUse an attribute for what the page sets and a state for what only the component knows, and spot the old
:--readysyntax.
What are custom states in web components?
Leaf and Kettle's brewing page is getting a kettle. A reader presses Boil, and the water heats while they read about green tea. Meena wants the kettle's border to turn green when the water is ready. But only the kettle knows when that is. The page can't see inside it.
Ravi, who builds the tea kit, could make the kettle add a ready attribute to itself. Then any page could add that attribute too, and lie. Is there a way to show a state that only the component can set?
A custom state is a name that a custom element turns on and off from inside its class, like ready. The class calls this.#internals.states.add("ready"), and CSS matches it with :state(ready): as tea-kettle:state(ready) on the page, or as :host(:state(ready)) inside the component. Anyone can read a state. Only the component can set it.
You've styled states before. In lesson 2.1, wa-button:state(disabled) styled Web Awesome's disabled button. Now you're the author. Here is the smallest kettle with a state:
<style> tea-kettle { display: inline-block; padding: 8px; border: 3px solid gray; } tea-kettle:state(ready) { border-color: seagreen; }</style><tea-kettle></tea-kettle> <script src="tea-kettle.js"></script><script> const kettle = document.querySelector("tea-kettle"); console.log("Ready?", kettle.matches(":state(ready)")); kettle.addEventListener("click", () => { console.log("Ready?", kettle.matches(":state(ready)")); });</script>- In the
tea-kettle.jstab, line 2 asks for the kettle's internals and keeps them in a private field,#internals. - Line 6 puts a Boil button in the kettle's shadow root. Line 8 runs on a click. It adds the name
readyto the kettle's states. - Back on the page, line 2 gives every kettle a gray border. Line 3 turns it sea green while the kettle is in the
readystate. - Line 10 asks the kettle if it's ready.
matches()takes a selector and says if the element fits it. Lines 11 to 13 ask again on every click.
It prints Ready? false as the page loads. Click Boil. The border turns sea green, and it prints Ready? true. The click starts at the button, so the kettle's own listener runs first. Then the click moves out to the page's listener on line 11, and the state is already there.
At Leaf and Kettle's counter, a small light sits above each order number. The kitchen turns it on when your tea is ready. You can see it from your table, and so can everyone else. But the switch is in the kitchen. You can't turn your own light on.
- In real life: The kitchen
- In CSS: The kettle's class
- In real life: The switch in the kitchen
- In CSS:
this.#internals.states - In real life: Your order's light coming on
- In CSS:
states.add("ready") - In real life: Seeing the light from your table
- In CSS:
tea-kettle:state(ready)in the page's CSS - In real life: No switch on your side of the counter
- In CSS: The page can't add a state
A custom state is a name that a custom element turns on and off from inside, through its internals. CSS reads it with :state(), inside and outside the component. Only the component can turn it on.
:state() works in every current browser. It's Baseline widely available.
How do you add a custom state with CustomStateSet?
States live in the element's internals. ElementInternals is an object a custom element can ask for once, with this.attachInternals(). Lesson 6.2 used it to reach a closed shadow root. This lesson uses one of its properties, states.
internals.states is a CustomStateSet: a list of names. It works like a JavaScript Set. A name is in it once, or not at all. It has these methods:
add(name)puts a name in. Adding it again changes nothing.delete(name)takes it out. It returnstrueif the name was there.has(name)asks if the name is there.clear()takes every name out.sizecounts the names. You can loop over the set, like any Set.
<tea-kettle></tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); connectedCallback() { const states = this.#internals.states; states.add("heating"); states.add("heating"); console.log("Size:", states.size); console.log("Heating?", states.has("heating")); states.delete("heating"); states.add("ready"); console.log("States:", [...states].join(", ")); } } customElements.define("tea-kettle", TeaKettle);</script>- Line 5 asks for the internals in a private field. Line 8 keeps their set in a shorter name.
- Lines 9 and 10 add
heatingtwice. Line 11 printsSize: 1. A name is in the set only once. - Line 12 prints
Heating? true. - Line 13 deletes
heating, and line 14 addsready. Line 15 spreads the set into an array and printsStates: ready.
So a state is a switch: on or off. The HTML Standard says the set shows true-or-false states, by whether a name is there or not.
Leaf and Kettle keeps a small chalk board behind the counter. Staff write short notices on it, like Busy or Out of scones. A word is on the board or it isn't. Writing Busy twice doesn't make the shop busier. Customers can read the board, but only staff hold the chalk.
- In real life: The chalk board
- In JavaScript: The state set,
this.#internals.states - In real life: Writing a word
- In JavaScript:
states.add("busy") - In real life: Wiping a word off
- In JavaScript:
states.delete("busy") - In real life: Looking for a word
- In JavaScript:
states.has("busy") - In real life: Only staff hold the chalk
- In JavaScript: Only the class holds the internals
What can a state's name be?
Chrome's add() takes any text at all. Its code puts the text in a list, and checks nothing about it. Then it asks the browser to check the host's styles again. But CSS has to name the state too. :state() takes a CSS identifier: one word of letters, digits, hyphens, and underscores, with no spaces, that doesn't start with a digit. Try four names:
<style> tea-kettle { display: inline-block; padding: 8px; border: 3px solid gray; } tea-kettle:state(ready) { border-color: seagreen; }</style><tea-kettle>Kettle</tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); connectedCallback() { this.#internals.states.add("ready"); console.log("States:", [...this.#internals.states].join(", ")); console.log(":state(ready) matches:", this.matches(":state(ready)")); } } customElements.define("tea-kettle", TeaKettle);</script>It prints States: ready and :state(ready) matches: true. The set holds ready, and :state(ready) asks for exactly that name. The border turns sea green.
- Line 12 is the only line that changes. It adds one name.
- Line 3 always asks for
:state(ready). Line 13 prints what the set holds. Line 14 asks if the selector matches.
With "ready", the border turns sea green. "Ready" doesn't match, because state names are case-sensitive. "--ready" keeps its dashes as part of the name. "ready heating" is one name with a space in it, not two states.
Why it matters: a state name is an exact string. Use lowercase words joined by hyphens, like has-notes, and spell it the same way in the class and in the CSS.
Only the class can set a state
A page has no way into the kettle's set. Here the page tries to get the internals of the kettle and of a div:
<tea-kettle></tea-kettle><div></div> <script src="tea-kettle.js"></script><script> for (const element of document.querySelectorAll("tea-kettle, div")) { try { element.attachInternals(); } catch (error) { console.log(`${element.localName}: ${error.name}`); } }</script>- Line 1 is the overview's kettle, from the
tea-kettle.jstab. Line 2 is a plain div. - Line 6 loops over both. Line 8 asks each one for its internals. Line 10 prints the error's name.
It prints tea-kettle: NotSupportedError and div: NotSupportedError. Chrome's messages give the two reasons. For the kettle: "ElementInternals for the specified element was already attached." The class asked first, on its line 2. For the div: "Unable to attach ElementInternals to non-custom elements."
attachInternals() call throws.So only a custom element has a state set. It must be an autonomous one, with its own tag name. Lesson 5.7 showed that attachInternals() throws for a customized built-in, like <button is="...">.
There is one catch. As lesson 6.2 warned, attachInternals() doesn't check who calls it. If the class never asks, a page can ask first, and then add any state it likes. So ask in a field or in the constructor, every time, and keep the result private with #. Exercise 5 shows the problem.
How does the :state() selector work?
Now the whole kettle. It has a light, a temperature, the word steam, and a Boil button. Boil heats the water for one second. The kettle styles its light from inside, and the page styles the rest from outside:
<style> tea-kettle { display: inline-block; padding: 8px; border: 3px solid gray; } tea-kettle:state(heating) { border-color: orange; } tea-kettle:state(ready) { border-color: seagreen; } tea-kettle:state(ready)::part(spout) { color: sienna; }</style><tea-kettle temperature="80"></tea-kettle> <script src="tea-kettle.js"></script>- In the
tea-kettle.jstab, line 2 watches thetemperatureattribute. Lines 21 to 23 show it. The page sets it on line 7. - Line 26 deletes
readyand line 27 addsheating. Lines 28 to 31 wait a second, then swapheatingforready. - Lines 10 and 11 color the light from inside.
:host(:state(heating))matches the kettle while it heats. Lesson 11.2 put:hoverinside:host()the same way. - Line 12 makes the steam silver. Line 16 names it as a part,
spout. - On the page, lines 3 and 4 color the border, one rule per state. Line 5 styles the spout while the kettle is ready.
Click Boil. The light and the border turn orange. A second later, both turn sea green, and the steam turns sienna. The page's rule beats the kettle's silver, because a page's ::part() rule beats the component's own, as lesson 12.2 showed.
Why two names and not one? The kettle has three moments: cold, heating, and ready. The HTML Standard shows how to turn a state with several values into several on-or-off names, with only one of them on at a time. Cold is no name at all. That's why line 26 deletes ready before line 27 adds heating.
:state() works anywhere a selector for the element works. MDN lists the places:
- inside the shadow root, in
:host()::host(:state(ready)); - on the page, after the tag:
tea-kettle:state(ready); - after
::part(), when the part is a custom element with states of its own.
It works in JavaScript too, in matches() and querySelectorAll(), and inside :not() and :is().
Where does :state() go next to ::part()?
A state and a part can meet in one selector. Where :state() sits decides whose state it asks about:
<style> tea-kettle:state(ready)::part(spout) { color: sienna; }</style><tea-kettle temperature="80"></tea-kettle> <script src="tea-kettle.js"></script>Click Boil. A second later, the steam turns sienna. :state(ready) asks about the kettle, and ::part(spout) then picks the steam inside it.
- Line 2 is the only line that changes. The
tea-kettle.jstab is the kettle from above. - Click Boil in the result, then watch the word steam for a second.
With :state(ready)::part(spout), the steam turns sienna once the kettle is ready. With :state(heating)::part(spout), it's sienna only while the kettle heats. With ::part(spout):state(ready), it never changes. That rule asks about the spout, a plain <span>, and a span has no states.
:state(ready) sits on the kettle, so it asks the kettle. In the second, it follows ::part(spout), so it asks the spout: a <span>, which has no states.Lesson 12.2's table listed :state() among the pseudo-classes that may follow ::part(). That form fits a part that is itself a custom element. MDN's example does this: a question box names its checkbox element as a part, and the page styles question-box::part(checkbox):state(checked).
Why it matters: put :state() right after the element that owns the state. For the host's state, that's before ::part().
What happened to the old :--state syntax?
Search for custom states, and you'll find examples like my-checkbox:--checked. That's the old syntax. It only ever worked in Chrome. Here is what happened:
- Chrome 90, in 2021, shipped custom states first. CSS wrote a state as
:--checked. JavaScript added it with the dashes, as"--checked". MDN notes that a name without them threw an error. - The standard then settled on
:state(checked). Safari 17.4 and Firefox 126 shipped only that form. - Chrome 125, in May 2024, added
:state(). Its release notes promised a window when both forms would work, so sites could switch.
That window has closed. Here is how Chrome reads an old rule now:
<style> tea-kettle:--ready { color: crimson; } tea-kettle:state(ready) { color: seagreen; }</style><tea-kettle>Kettle</tea-kettle> <script> const rules = document.querySelector("style").sheet.cssRules; console.log("Rules kept:", rules.length); console.log(rules[0].selectorText);</script>- Line 2 is a rule in the old syntax. Line 3 is the same rule in today's.
- Line 9 prints how many rules Chrome kept. Line 10 prints the first one's selector.
It prints Rules kept: 1 and tea-kettle:state(ready). Chrome dropped line 2, as it drops any selector it can't read. No error tells you. In JavaScript, a name with two dashes is now just a name, as the names playground showed. Only :state(--ready) would match it.
:state(ready), and Chrome drops a :--ready rule.The road outside Leaf and Kettle got a new name. For a few months, the post office took letters with either name. Then the old name stopped working. A letter with it now never arrives, and nobody tells the sender.
- In real life: The old street name
- In CSS:
:--ready - In real life: The new street name
- In CSS:
:state(ready) - In real life: The months when both names worked
- In CSS: The window after Chrome 125
- In real life: A letter that never arrives
- In CSS: A rule Chrome drops, with no error
The table puts the two forms side by side. Read each row across:
| Where the name goes | Chrome 90 to 124 | Every browser today |
|---|---|---|
| In CSS | tea-kettle:--ready | tea-kettle:state(ready) |
| In JavaScript | states.add("--ready"), with the dashes. | states.add("ready"), with no dashes. |
| A name with no dashes | add("ready") threw an error. | It works. Names are plain words. |
| Firefox and Safari | They never supported it. | Firefox 126 and Safari 17.4 support it. |
Lesson 1.2 listed this change among the old names to watch for. Why it matters: when you copy an older example, change both sides. Write :state(ready) in the CSS and add("ready") in the class.
Should you use a custom state or an attribute?
The kettle has both. Its temperature is an attribute. Its readiness is a state. Why not make ready an attribute too? Lesson 8.4's card did just that with has-notes.
A kettle on the stove has a knob and a whistle. You turn the knob to pick the heat. The kettle whistles on its own when the water boils, and everyone in the kitchen hears it. Whistling at the kettle yourself doesn't boil the water.
- In real life: The knob you turn
- In HTML: An attribute the page sets,
temperature="90" - In real life: The whistle
- In HTML: A custom state,
ready - In real life: The water boiling
- In HTML: The kettle's own code, which adds the state
- In real life: Everyone hearing the whistle
- In HTML:
:state(ready)in any style sheet - In real life: Whistling at the kettle yourself
- In HTML: A page trying to set the state
So the first question is who sets it. If the page should be able to set it, use an attribute. If only the component knows it, use a state. Chrome's styling guide says a state is read-only from outside: pages can style it, but can't set or forge it. It advises a state whenever the component owns it and it only needs styling.
The two also look different to the rest of the page. Watch both change:
<tea-kettle temperature="80"></tea-kettle><button id="knob">Turn the knob to 90</button><button id="html">Print the HTML</button> <script src="tea-kettle.js"></script><script> const kettle = document.querySelector("tea-kettle"); new MutationObserver((records) => { for (const record of records) console.log("Changed:", record.attributeName); }).observe(kettle, { attributes: true }); document.querySelector("#knob").onclick = () => kettle.setAttribute("temperature", "90"); document.querySelector("#html").onclick = () => { console.log(kettle.outerHTML); console.log("Ready?", kettle.matches(":state(ready)")); };</script>- Line 1 sets the knob:
temperature="80". - Lines 8 to 10 watch the kettle's attributes with a
MutationObserver. It prints the name of each attribute that changes. - Line 11 turns the knob from the page. Lines 12 to 15 print the kettle's HTML and whether it's ready.
Click Boil, wait for the green light, then click Print the HTML. It prints <tea-kettle temperature="80"></tea-kettle> and Ready? true. The state is on, but the HTML doesn't show it, and the observer printed nothing. Now click Turn the knob to 90. It prints Changed: temperature, and the kettle shows 90 °C.
Here is how the two differ. Read each row across:
| The question | An attribute | A custom state |
|---|---|---|
| Who sets it? | The page, in HTML or with setAttribute(). The component can too. | Only the component, through its internals. |
| Can the page change it? | Yes. Anyone can add, change, or remove it. | No. The page has no way to reach the set. |
| What can it hold? | Any text, like temperature="90". | A name that is there or not there, like ready. |
| Does it show in the HTML? | Yes, in outerHTML and in the Elements panel's markup. | No. outerHTML stays the same. |
| Does a MutationObserver see it change? | Yes. Each change makes a record. | No. It makes no records. |
Does cloneNode() copy it? | Yes. | No. The copy starts with no states. |
| How does CSS select it? | tea-kettle[temperature="90"] | tea-kettle:state(ready) |
| Does a screen reader hear it? | Only ARIA attributes, like aria-checked. | No. It's for styling only. |
Why it matters: nothing announces a state change. If a script needs to know when it changes, fire an event as well, the way lesson 5.3's timer announces it's done with tea-timer-done.
Should a component copy a state to an attribute?
When a component adds attributes the page never wrote, people call it sprouting attributes. Cory LaViska, who created Shoelace, writes that it's largely seen as an anti-pattern. Attributes are meant to be the page's input. He also points out that native elements do it: <details> adds open when it opens. His view is that a component may set an attribute and a custom state together, and let the page pick which one to style.
Lesson 5.1 said to reflect sparingly, and not to add an attribute the page didn't write just to show a default. For a state only the component knows, a custom state is enough. Keep a copied attribute only when pages already depend on it, as the kit does in the next section.
What about values, like a size?
A state is only on or off. For a value, you could add one state per choice, like size-small and size-large. LaViska looked at this for a badge's variants, and wrote that it gets messy for values that aren't true or false. A size is something the page chooses anyway. So it's an attribute: size="large".
Do screen readers hear custom states?
No. A state is for styling only. It doesn't reach the accessibility tree, the version of the page that screen readers use. Give a custom checkbox a checked state, and Chrome's accessibility tree still says it isn't checked. It needs a role and aria-checked too. Accessible components sets them with the same internals. The internals also let a component join a form, which Forms covers.
Sort these by who should set them:
- The water in the kettle has boiled
- The temperature the page wants the water at
- The card's slot holds tasting notes
- The tea's name on a card
- An order form is sending the order
- A small or a large kettle, chosen by the page
Put each one where it belongs: an attribute the page sets, or a state only the component sets.
Giving the tea kit a custom state
Back to the kit. Lesson 8.4's card sets a has-notes attribute on itself when its default slot holds tasting notes. Its docs say: read it, don't set it. Only the card can look in its slot, so this is a state. Lesson 11.3 pointed here for this change. In the kit's tea-card.js:
- Line 70 asks for the internals in a private field, before any page can.
- Lines 98 and 99 add the
has-notesstate when there are notes, and delete it when there aren't. - Line 14 hides the Tasting notes heading from inside, with
:host(:not(:state(has-notes))) #notes. The script no longer hides it, so the<h4>on line 25 lost itshiddenattribute. - Line 100 still sets the old attribute, so pages that style
tea-card[has-notes]keep working. The docs now mark it deprecated.
Meena styles the cards that have notes:
<style> tea-card:state(has-notes) { --tea-card-bg: ivory; } tea-card:state(has-notes)::part(name) { font-style: italic; }</style><tea-card name="Green tea" price="4"></tea-card><tea-card name="Oolong" price="5"><p>Toasted, with a honey finish.</p></tea-card> <script type="module"> import "./tea-kit/index.js"; setTimeout(() => { for (const card of document.querySelectorAll("tea-card")) { console.log(card.getAttribute("name"), card.matches(":state(has-notes)")); } console.log("Without notes:", document.querySelectorAll("tea-card:not(:state(has-notes))").length); });</script>- Line 2 gives cards with notes an ivory background, through lesson 12.1's
--tea-card-bg. Line 3 puts their name part in italics. - Lines 5 and 6 are two cards. Only Oolong has notes.
- Line 10 waits for the next task, so the cards'
slotchangeevents have run. Lines 11 to 13 print each card's state. Line 14 counts the cards without notes.
It prints Green tea false, Oolong true, and Without notes: 1. Oolong's card is ivory, with its name in italics. A page could still write has-notes on a card with no notes, and a tea-card[has-notes] rule would believe it. A :state(has-notes) rule can't be fooled.
Documenting a state with @cssstate
The analyzer's docs list @cssState for custom states. Its code reads the lowercase @cssstate too, which matches the kit's @csspart and @cssprop. Here is the card's JSDoc, shortened:
/**
* A tea card: a tea's name and price in a box, with a quantity and an Add button. Its own shadow root holds them.
*
* @tag tea-card
* @attr {boolean} has-notes - Deprecated: style :state(has-notes) instead. Set by the card itself while its default slot holds tasting notes.
* @cssstate has-notes - The card's default slot holds tasting notes. Only the card sets it.
*/- Line 5 is the old attribute. Its description now starts with Deprecated and says what to use instead.
- Line 6 is the state: its name, a dash, and what it means.
The analyzer puts states in a cssStates list. The kit writes its manifest by hand, to match. Lesson 2.1 saw the same list for wa-button, with disabled and loading:
"cssStates": [
{
"name": "has-notes",
"description": "The card's default slot holds tasting notes. Only the card sets it."
}
]Lines 2 to 5 describe has-notes. The manifest's schema notes that a state's name has no leading --, unlike a custom property's. The old attribute's entry gets a deprecated note that names the state.
Common mix-ups
- "A custom state is a kind of attribute." No. It never shows in the HTML, and a
MutationObservernever sees it change. - "
:--readyis a short way to write:state(ready)." No. It's the old syntax, which only Chrome had. Chrome now drops the whole rule. - "A page can add a state with
kettle.states.add()." No. Elements have nostatesproperty. Only the internals have one, and the class keeps them. - "Any element can have custom states." No. Only autonomous custom elements can.
attachInternals()throws for a div and for a customized built-in. - "
tea-kettle::part(spout):state(ready)styles the steam while the kettle is ready." No. It asks about the spout's own states. Writetea-kettle:state(ready)::part(spout). - "
states.add("ready heating")adds two states." No. It adds one name with a space in it, which no selector can match. - "A checked state tells screen readers the box is checked." No. States are for styling. A checkbox still needs a role and
aria-checked.
Practice exercises
Answer first, then use the hints. The pages run live, so you can check yourself.
The kettle adds three names and deletes one. What does the page print?
<tea-kettle></tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); connectedCallback() { const states = this.#internals.states; states.add("heating"); states.add("ready"); states.add("heating"); states.delete("cold"); console.log("Size:", states.size); } } customElements.define("tea-kettle", TeaKettle);</script>Size: 2. The set holds heating and ready. The second heating changes nothing, and deleting cold does nothing, because it was never there.
The page presses Boil on the first and third kettles, then counts them with querySelectorAll(). What does the first line print?
<tea-kettle temperature="80"></tea-kettle><tea-kettle temperature="90"></tea-kettle><tea-kettle temperature="100"></tea-kettle> <script src="tea-kettle.js"></script><script> const kettles = document.querySelectorAll("tea-kettle"); kettles[0].shadowRoot.querySelector("button").click(); kettles[2].shadowRoot.querySelector("button").click(); console.log("Heating:", document.querySelectorAll("tea-kettle:state(heating)").length); console.log("Ready:", document.querySelectorAll("tea-kettle:state(ready)").length);</script>Heating: 2. Boil adds heating at once, so two kettles match tea-kettle:state(heating). The next line prints Ready: 0, because no second has passed yet.
This snippet comes from an old blog post. It prints Border: rgb(128, 128, 128), gray. Bring it up to date. What does it print then?
<style> tea-kettle { display: inline-block; padding: 8px; border: 3px solid gray; } tea-kettle:--ready { border-color: seagreen; }</style><tea-kettle>Kettle</tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); connectedCallback() { this.#internals.states.add("--ready"); } } customElements.define("tea-kettle", TeaKettle); console.log("Border:", getComputedStyle(document.querySelector("tea-kettle")).borderTopColor);</script><style> tea-kettle { display: inline-block; padding: 8px; border: 3px solid gray; } tea-kettle:state(ready) { border-color: seagreen; }</style><tea-kettle>Kettle</tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); connectedCallback() { this.#internals.states.add("ready"); } } customElements.define("tea-kettle", TeaKettle); console.log("Border:", getComputedStyle(document.querySelector("tea-kettle")).borderTopColor);</script>Chrome dropped the old rule, and the name kept its dashes. With today's form on both sides, the rule matches, and it prints Border: rgb(46, 139, 87), sea green.
The kettle is ready, but its light stays gray. Add one rule inside the shadow root to turn it sea green. What does the page print then?
<tea-kettle></tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> .light { display: inline-block; width: 12px; height: 12px; background: gray; } </style> <span class="light"></span> Kettle`; } connectedCallback() { this.#internals.states.add("ready"); } } customElements.define("tea-kettle", TeaKettle); const light = document.querySelector("tea-kettle").shadowRoot.querySelector(".light"); console.log("Light:", getComputedStyle(light).backgroundColor);</script><tea-kettle></tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); constructor() { super(); this.attachShadow({ mode: "open" }).innerHTML = ` <style> .light { display: inline-block; width: 12px; height: 12px; background: gray; } :host(:state(ready)) .light { background: seagreen; } </style> <span class="light"></span> Kettle`; } connectedCallback() { this.#internals.states.add("ready"); } } customElements.define("tea-kettle", TeaKettle); const light = document.querySelector("tea-kettle").shadowRoot.querySelector(".light"); console.log("Light:", getComputedStyle(light).backgroundColor);</script>The new rule, :host(:state(ready)) .light { background: seagreen; }, matches while the host has the ready state. It prints Light: rgb(46, 139, 87).
This page prints Forged: true: it gave the kettle a ready state. Change one line of the class so it can't. What does the page print then?
<style> tea-kettle:state(ready) { outline: 3px solid seagreen; }</style><tea-kettle>Kettle</tea-kettle> <script> class TeaKettle extends HTMLElement { #internals; boil() { this.#internals ??= this.attachInternals(); this.#internals.states.add("ready"); } } customElements.define("tea-kettle", TeaKettle); // Somewhere else on the page: const kettle = document.querySelector("tea-kettle"); try { kettle.attachInternals().states.add("ready"); console.log("Forged:", kettle.matches(":state(ready)")); } catch (error) { console.log("Forged:", error.name); }</script><style> tea-kettle:state(ready) { outline: 3px solid seagreen; }</style><tea-kettle>Kettle</tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); boil() { this.#internals ??= this.attachInternals(); this.#internals.states.add("ready"); } } customElements.define("tea-kettle", TeaKettle); // Somewhere else on the page: const kettle = document.querySelector("tea-kettle"); try { kettle.attachInternals().states.add("ready"); console.log("Forged:", kettle.matches(":state(ready)")); } catch (error) { console.log("Forged:", error.name); }</script>Now the class asks first, as the kettle is made. The page's call throws, so it prints Forged: NotSupportedError. boil() still works: ??= keeps the internals the field already holds.
The page writes has-notes on an empty card, and the heading shows: Heading: block. Change the tea-card.js tab to use a has-notes state. What does the page print then?
<tea-card></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); card.setAttribute("has-notes", ""); console.log("Heading:", getComputedStyle(card.shadowRoot.querySelector("h4")).display);</script><tea-card></tea-card> <script src="tea-card.js"></script><script> const card = document.querySelector("tea-card"); card.setAttribute("has-notes", ""); console.log("Heading:", getComputedStyle(card.shadowRoot.querySelector("h4")).display);</script>See the tea-card.js tab: a #internals field, a rule that reads :state(has-notes), and a listener that adds or deletes the state. Only the card can set it, so the page's fake attribute changes nothing. The empty card prints Heading: none.
Check your understanding
For each question, ask: who sets it, and which element owns it?
Question 1 of 7What does
this.#internals.states.add("ready")do in the kettle's class?Choose an answer to see the explanation.
Question 2 of 7The kettle adds
Readywith a capital R. What does this page print?Read the code, then predict<tea-kettle></tea-kettle> <script> class TeaKettle extends HTMLElement { #internals = this.attachInternals(); connectedCallback() { this.#internals.states.add("Ready"); } } customElements.define("tea-kettle", TeaKettle); console.log(document.querySelector("tea-kettle").matches(":state(ready)")); </script>Choose an answer to see the explanation.
Question 3 of 7The kettle's steam is a part named
spout, and the kettle has areadystate. Which page rule styles the steam while the kettle is ready?Choose an answer to see the explanation.
Question 4 of 7A 2022 blog post styles
tea-kettle:--ready. What does Chrome do with that rule today?Choose an answer to see the explanation.
Question 5 of 7A page should choose the kettle's size, small or large. How should the kettle offer that?
Choose an answer to see the explanation.
Question 6 of 7A MutationObserver watches the kettle's attributes. The kettle adds
ready, then the page setstemperature. How many records does the observer get?Choose an answer to see the explanation.
Question 7 of 7A custom checkbox adds a
checkedstate when you click it. What does a screen reader learn from that state?Choose an answer to see the explanation.
Key takeaways
- A custom element asks for its internals once:
#internals = this.attachInternals();. Ask in every class, so no page can ask first. internals.statesis a CustomStateSet, a set of names withadd(),delete(),has(),clear(), andsize.- CSS matches a state with
:state(ready)::host(:state(ready))inside,tea-kettle:state(ready)outside, and inmatches()andquerySelectorAll(). - Put
:state()after the element that owns it:tea-kettle:state(ready)::part(spout)for the host's state. - The old
:--readysyntax was Chrome-only, and Chrome drops it now. Write:state(ready)andadd("ready"). - Use an attribute for what the page sets, and a state for what only the component knows. A state doesn't show in the HTML, makes no observer records, and doesn't reach screen readers.
Remember the one-liner.
The page turns the knob. Only the kettle whistles, and everyone can hear it.
Sources
The facts on this page come from these standards, docs, and posts:
- :state(), MDN.
- CustomStateSet, MDN.
- ElementInternals: states property, MDN.
- Using custom elements: Custom states and custom state pseudo-class CSS selectors, MDN.
- HTML Standard: Custom state pseudo-class, WHATWG.
- HTML Standard: The :state() pseudo-class, WHATWG.
- HTML Standard: attachInternals(), WHATWG.
- custom_state_set.cc at 158.0.8127.18, Chromium.
- Chrome 125 release notes: New syntax for CSS custom :state(), Chrome for Developers.
- Styling web components: :state(), Chrome for Developers, Modern Web Guidance.
- Reflection and Custom States in Web Components, Cory LaViska.
- Styling Custom Elements Without Reflecting Attributes, Cory LaViska.
- Custom Elements Manifest Analyzer: Supported JSDoc, Open Web Components.
- class-jsdoc.js in the Custom Elements Manifest analyzer 0.11.0, Open Web Components.
- The Custom Elements Manifest schema, webcomponents.org.
Coming next: Page styles for components, in Styling web components. Not every style lives in a shadow root. The next lesson covers what the page's own styles still do for components.