The :host-context()
CSS pseudo-class function selects the shadow host of the shadow DOM containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the DOM hierarchy.
In other words, this allows a custom element, or anything within that custom element's shadow DOM, to apply different styles based on its position within the outer DOM or classes/attributes applied to ancestor elements.
One typical use of this is with a descendant selector expression — for example h1
— to select only instances of the custom element that are inside an <h1>
. Another typical use would be to allow inner elements to react to classes or attributes on any ancestor elements - for example, applying a different text color when a .dark-theme
class is applied to <body>
.
Note: This has no effect when used outside a shadow DOM.
/* Selects a shadow root host, only if it is a descendant of the selector argument given */ :host-context(h1) { font-weight: bold; } :host-context(main article) { font-weight: bold; } /* Changes paragraph text color from black to white when a .dark-theme class is applied to the document body */ p { color: #000; } :host-context(body.dark-theme) p { color: #fff; }