CSS Reference ยท Pseudo-classes
The :state() pseudo-class
Reference for the CSS :state() pseudo-class: style custom elements by named states set through ElementInternals, with a live custom element example.
The :state() pseudo-class matches a custom element that has a named, author-defined state. The element's JavaScript adds or removes the state, and the page's CSS reacts to it, just like built-in states such as :checked or :disabled.
This replaces the habit of toggling classes or attributes on a component only to style it.
toggle-switch:state(on) { background: seagreen; }
// inside the custom element class this.internals = this.attachInternals(); this.internals.states.add("on");
Try it
Syntax
custom-element:state(<ident>) { /* declarations */ }
Specificity (0,1,0). The argument is an identifier (no quotes) that must match a string added to internals.states.
Syntax and arguments
| Part | Description |
|---|---|
:state(name) |
Matches a custom element whose ElementInternals.states set contains name. |
states.add(name) |
JavaScript side: turns the state on. |
states.delete(name) |
Turns the state off. |
states.has(name) |
Checks the state. |
Usage notes
- For custom elements only. Built-in elements have no custom states, and the element needs
attachInternals()in its class. - Part of the public API. Name states like attributes or events; users of your component rely on them. Document them.
- Dashed idents are fine. Use plain identifiers such as
loadingorhas-error. - Shadow DOM. To style a state of an element inside a shadow tree from outside, expose the element with
partand combine::part(name):state(on). - Older syntax. Early Chrome versions used a
--namedashed form (:--name). Current code should use:state(name)and ignore the old form. - Not a replacement for ARIA. If the state matters to assistive technology, also expose the right ARIA through
ElementInternals.
Browser support
Supported in current versions of Chrome, Edge, Firefox and Safari; Baseline newly available since 2024.
Related
:definedโ registered custom elements:hostโ the shadow host::part()โ shadow parts- Lessons: Pseudo-classes, Selector functions