Skip to content
Tutorials Center
My learning

Topics

CSS Reference ยท Pseudo-classes

The :host pseudo-class

Reference for the CSS :host and :host() pseudo-classes: style a custom element from inside its shadow tree, with a shadow DOM example and specificity notes.

The :host pseudo-class selects the shadow host: the element that a shadow root is attached to. It only works in CSS that lives inside the shadow tree (a <style> in the shadow root or an adopted stylesheet). It is how a web component sets its own defaults, such as display, without the page having to do it.

The functional form :host(selector) matches the host only when it also matches the selector, for example :host(.active) or :host([disabled]).

CSS
:host {
  display: block;
  border: 2px solid teal;
}
:host([disabled]) {
  opacity: 0.5;
}

Try it

A component styling its own host

Syntax

CSS
:host { /* declarations */ }
:host(<compound-selector>) { /* declarations */ }
:host-context(<compound-selector>) { /* declarations */ }

:host has the specificity of a pseudo-class (0,1,0); :host() adds the specificity of its argument.

Syntax and arguments

Part Description
:host The shadow host, always.
:host(.x), :host([attr]) The host, only if it matches the compound selector given.
:host-context(.x) The host when it or an ancestor matches the selector. Supported only in Chromium-based browsers; avoid it.
Outside a shadow tree Matches nothing.

Usage notes

  • Outer styles win. A rule for the same element in the page's own CSS beats a :host rule regardless of specificity, because the outer (light DOM) context is stronger for normal declarations. Use :host for defaults, not guarantees.
  • Set display. A custom element is display: inline by default. Most components should set :host { display: block } (or inline-block).
  • Custom properties are the API. Inherited custom properties pass through the shadow boundary, so components can read --accent set by the page, and :host can set sensible fallbacks.
  • Only compound selectors. :host(.a .b) is invalid; the argument cannot contain combinators.
  • :host also works in <style> inside <template> content that gets cloned into the shadow root.

Browser support

:host and :host() are supported in all current browsers and Baseline widely available. :host-context() works only in Chromium-based browsers.