:host
:host CSS 伪类 用于选择包含其所使用的 CSS 的 shadow DOM 的宿主——换句话说,这允许你从自定义元素的 shadow DOM 内部选择该自定义元素。
注意:在 shadow DOM 外部使用时,此伪类无效。
试一试
/* This CSS is being applied inside the shadow DOM. */
:host {
background-color: aqua;
}
<h1 id="shadow-dom-host"></h1>
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;
}
css
/* Selects a shadow root host */
:host {
font-weight: bold;
}
语法
css
:host {
/* ... */
}
示例
样式化 shadow 宿主
以下代码片段取自我们的 host-selectors 示例(也可在线查看)。
在此示例中,我们有一个基本的自定义元素——<context-span>——你可以用它来包裹文本。
html
<h1>
Host selectors <a href="#"><context-span>example</context-span></a>
</h1>
在元素的构造函数中,我们创建 style 和 span 元素,用自定义元素的内容填充 span,并用一些 CSS 规则填充 style 元素
js
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-context(article, aside) { color: gray; }" +
":host(.footer) { color : red; }" +
":host { background: rgb(0 0 0 / 10%); padding: 2px 5px; }";
:host { background: rgb(0 0 0 / 10%); padding: 2px 5px; } 规则为文档中所有 <context-span> 元素(在此实例中为 shadow 宿主)设置样式。
规范
| 规范 |
|---|
| CSS 作用域模块级别 1 # 宿主选择器 |
浏览器兼容性
加载中…