# :state()

> The `:state()` CSS pseudo-class selects custom elements that have the specified custom state.

## How do I style custom states of a web component in CSS?

The pseudo-class that matches custom elements by states they expose through `CustomStateSet`, for example `:state(checked)`. Allows styling internal states of web components the same way as built-in pseudo-classes.

- Topic: Pseudo Classes
- Type: pseudo-class
- Browser support: Chrome 125+, Chrome Android 125+, Edge 125+, Firefox 126+, Firefox Android 126+, Safari 17.4+, Safari iOS 17.4+

## Example

Wrong:

```js
class XToggle extends HTMLElement {
  set checked(v) {
    this.classList.toggle('checked', v);
  }
}
```

Right:

```js
class XToggle extends HTMLElement {
  #internals = this.attachInternals();
  set checked(v) {
    if (v) this.#internals.states.add('checked');
    else this.#internals.states.delete('checked');
  }
}
```

A custom state is owned by the element, so `x-toggle:state(checked)` matches without exposing a class the page can change.

## Common mistakes

- Writing the old `:--checked` selector syntax instead of `:state(checked)`.

## Key points

- States are set with `internals.states.add('checked')` after `attachInternals()`.
- Selectors use `:state(checked)`, not the old `:--checked` syntax.
- Custom states don't replace ARIA: roles and `aria-*` values are still set for assistive tech.

## Interview questions

### Can I use :state() inside the shadow DOM?

Yes. Inside the component styles use `:host(:state(checked))`; from the page use `x-toggle:state(checked)`.

### What is the difference between :state() and a class?

Any script can add or remove a class. A custom state is set only by the element through `ElementInternals`, so it works like a built-in pseudo-class.

## Related cards

- [Web Components](https://wonderium.dev/web/web-components.md)
- [Shadow DOM](https://wonderium.dev/js/shadow-dom.md)
- [Pseudo-class](https://wonderium.dev/css/pseudo-class.md)
- [\[aria-checked\]](https://wonderium.dev/a11y/aria-checked.md)
- [`<slot>`](https://wonderium.dev/html/slot.md)

---

- Level: [CSS](https://wonderium.dev/css.md)
- HTML version: https://wonderium.dev/css/state
- Last updated: 2026-11-25
