:host-context()
The :host-context() CSS pseudo-class allows you to style elements within a shadow DOM differently based on the selector of the shadow host (the element that has the shadow root) and its DOM ancestors.
Normally, elements within a shadow DOM are isolated from the DOM outside of it. The :host-context() allows you to "peek outside" of this Shadow DOM and check if any of the element's ancestor elements match a certain CSS selector. For example, applying a different text color to elements within a shadow root when a .dark-theme class is applied to <body>.
Think of it like this: Imagine you have a <greenhouse> custom element, that has a <chameleon> living inside. Here, the <greenhouse> is the Shadow DOM host and the <chameleon> element is within the Shadow DOM. The :host-context() lets the <chameleon> change its appearance based on the <greenhouse>'s environment. If the <greenhouse> is in a sunny location (has a "sunny-theme" class), the <chameleon> turns yellow. If the <greenhouse> is in a shady spot (a "shady-theme" class applied instead), the <chameleon> turns blue.
This selector pierces through all shadow boundaries. It will look for the sunny or shady theme applied directly to the <greenhouse> or on any of the host's ancestors and ancestor DOMs all the way up until it reaches the document root.
To limit the selector to only the <greenhouse> host directly or limit the selection to host's DOM, use the :host or :host() pseudo-class instead.
The specificity of :host-context() is that of a pseudo-class, plus the specificity of the selector passed as the function's argument.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
:host-context Deprecated | 54 | 79 | | | 54 | |
Syntax
:host-context(.dark-theme) {
background: #333;
color: #fff;
}
:host-context([dir='rtl']) {
direction: rtl;
} Live demo
Use cases
-
Using :host-context()
The :host-context() CSS pseudo-class allows you to style elements within a shadow DOM differently based on the selector of the shadow host (the element that has the shadow root) and its DOM ancestors.
Cautions
- Limited browser support. Check compatibility before use.
Accessibility
- Make sure visual changes are conveyed appropriately to assistive technology.