/* Following CSS is being applied inside the shadow DOM. */
:host-context(.container) {
border: 5px dashed green;
}
:host-context(h1) {
color: red;
}
<!-- elements outside shadow dom -->
<div class="container">
<h1 id="shadow-dom-host"></h1>
</div>
const shadowDom = init();
// add a <span> element in the shadow DOM
const span = document.createElement("span");
span.textContent = "Inside shadow DOM";
shadowDom.appendChild(span);
// attach shadow DOM to the #shadow-dom-host element
function init() {
const host = document.getElementById("shadow-dom-host");
const shadowDom = host.attachShadow({ mode: "open" });
const cssTab = document.querySelector("#css-output");
const shadowStyle = document.createElement("style");
shadowStyle.textContent = cssTab.textContent;
shadowDom.appendChild(shadowStyle);
cssTab.addEventListener("change", () => {
shadowStyle.textContent = cssTab.textContent;
});
return shadowDom;
}
/* Selects a shadow root host, only if it is
a descendant of the selector argument given */
:host-context(h1) {
font-weight: bold;
}
/* Changes paragraph text color from black to white when
a .dark-theme class is applied to the document body */
p {
color: black;
}
:host-context(body.dark-theme) p {
color: white;
}
Syntax
:host-context(<compound-selector>) {
/* ... */
}
Examples Selectively styling shadow hosts
The following snippets are taken from our host-selectors example (see it live also).
In this example we have a basic custom element â <context-span>
â that you can wrap around text:
<h1>
Host selectors <a href="#"><context-span>example</context-span></a>
</h1>
Inside the element's constructor, we create style
and span
elements, fill the span
with the content of the custom element, and fill the style
element with some CSS rules:
const style = document.createElement("style");
const span = document.createElement("span");
span.textContent = this.textContent;
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(style);
shadowRoot.appendChild(span);
style.textContent =
"span:hover { text-decoration: underline; }" +
":host-context(h1) { font-style: italic; }" +
':host-context(h1)::after { content: " - no links in headers!" }' +
":host(.footer) { color : red; }" +
":host { background: rgb(0 0 0 / 10%); padding: 2px 5px; }";
The :host-context(h1) { font-style: italic; }
and :host-context(h1)::after { content: " - no links in headers!" }
rules style the instance of the <context-span>
element (the shadow host in this instance) inside the <h1>
. We've used it to make it clear that the custom element shouldn't appear inside the <h1>
in our design.
Loadingâ¦
See also:host
pseudo-class:host()
pseudo-class:state()
pseudo-class::slotted
pseudo-element<template>
elementRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.5