: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 # 宿主選擇器 |
瀏覽器相容性
載入中…