:host

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020.

:hostCSS擬似クラスで、その CSS を含むシャドウ DOM のシャドウホストを選択します。 — 言い換えれば、シャドウ DOM の中からカスタム要素を選択できるようにします。

メモ: これはシャドウ DOM の外で使われたときには効果がありません。

試してみましょう

css
/* シャドウのルートホストを選択 */
:host {
  font-weight: bold;
}

構文

css
:host {
  /* ... */
}

シャドウホストのスタイル付け

以下のスニペットは、 host セレクターの例ライブでも参照)から取りました。

この例では、テキストの周りを囲むことができる簡単なカスタム要素 — <context-span> — を使います。

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

要素のコンストラクターの中で、 style および span 要素を作成し、 span の中をカスタム要素の中身で埋め、 style 要素をいくつかの CSS ルールで埋めます。

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: rgba(0 0 0 / 10%); padding: 2px 5px; } のルールは、文書中の <context-span> 要素(このインスタンスのシャドウホスト)のすべてのインスタンスにスタイル付けします。

仕様書

Specification
CSS Scoping Module Level 1
# host-selector

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
:host

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報