:host-context()
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
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.
Note: This has no effect when used outside a shadow DOM.
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()
Deprecated: This feature is no longer recommended.
Cautions
- Limited browser support. Check compatibility before use.
Accessibility
- Make sure visual changes are conveyed appropriately to assistive technology.