このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

:host

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2020年1月⁩.

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

メモ: これはシャドウ 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
/* シャドウのルートホストを選択 */ :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

ブラウザーの互換性

関連情報