:host()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

:host() CSS 偽類函式用於選擇包含該 CSS 的 Shadow DOM 的 Shadow Host(這樣你就可以從自定義元素的 Shadow DOM 內部選擇該自定義元素)——但前提是作為函式引數給出的選擇器匹配 Shadow Host。當在 Shadow DOM 外部使用時,:host() 沒有效果。

最明顯的用法是僅將類名新增到某些自定義元素例項上,然後將相關的類選擇器作為函式引數包含在內。你不能將其與後代選擇器表示式一起使用,來僅選擇位於特定祖先元素內的自定義元素例項。那是 :host-context() 的職責。

注意:雖然其他函式式偽類(例如 :is():not())接受選擇器列表作為其引數,但 :host() 接受單個複合選擇器作為其引數。此外,雖然 :is():not() 僅考慮其引數的特殊性,但 :host() 的特殊性既是偽類的特殊性,又是其引數的特殊性。

試一試

/* Following CSS is being applied inside the shadow DOM. */

:host(h1) {
  color: red;
}

:host(#shadow-dom-host) {
  border: 2px dashed blue;
}
<!-- elements outside shadow dom -->
<div id="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;
}
css
/* Selects a shadow root host, only if it is
   matched by the selector argument */
:host(.special-custom-element) {
  font-weight: bold;
}

語法

css
:host(<compound-selector>) {
  /* ... */
}

示例

選擇性地為 Shadow Host 設定樣式

以下程式碼片段取自我們的 host-selectors 示例也可線上檢視)。

在此示例中,我們有一個自定義元素 — <context-span> — 你可以將其包裝在文本週圍。

html
<h1>
  Host selectors <a href="#"><context-span>example</context-span></a>
</h1>

在元素的建構函式中,我們建立 stylespan 元素,用自定義元素的內容填充 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(.footer) { color : red; } 規則會樣式化文件中所有具有 footer 類(在此例項中為 Shadow Host)的 <context-span> 元素例項 — 我們已將其用於為 <footer> 內部的元素例項設定特殊顏色。

規範

規範
CSS 作用域模組級別 1
# 宿主選擇器

瀏覽器相容性

另見