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]).
:host { display: block; border: 2px solid teal; } :host([disabled]) { opacity: 0.5; }
Try it
Syntax
: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
:hostrule regardless of specificity, because the outer (light DOM) context is stronger for normal declarations. Use:hostfor defaults, not guarantees. - Set
display. A custom element isdisplay: inlineby default. Most components should set:host { display: block }(orinline-block). - Custom properties are the API. Inherited custom properties pass through the shadow boundary, so components can read
--accentset by the page, and:hostcan set sensible fallbacks. - Only compound selectors.
:host(.a .b)is invalid; the argument cannot contain combinators. :hostalso 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.
Related
:definedโ registered custom elements::slotted()โ slotted content::part()โ exposed shadow parts- Lessons: Pseudo-classes, Selectors