このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
: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月.
:host() はCSS の擬似クラス関数で、その中で使われている CSS を含むシャドウ DOM のシャドウホストを選択します(従ってカスタム要素をそのシャドウ DOM 内部から選択できます)。ただし、関数の引数として与えられたセレクターがシャドウホストと一致した場合のみです。:host() はシャドウ DOM の外で使用しても効果はありません。
この最も明白な使用法は、特定のカスタム要素インスタンスにのみクラス名を付け、関数の引数として関連するクラスセレクターを指定することです。特定の祖先の内部にあるカスタム要素のインスタンスのみを選択するために、子孫セレクター式でこれを使用することはできません。それは:host-context() の仕事です。
In this article
試してみましょう
/* この CSS はシャドウ DOM の内部に適用されます。 */:host(h1) { color: red;}:host(#shadow-dom-host) { border: 2px dashed blue;}<!-- シャドウ DOM の外側の要素 --><div> <h1></h1></div>const shadowDom = init();// シャドウ DOM に <span> 要素を追加const span = document.createElement("span");span.textContent = "シャドウ DOM の内部";shadowDom.appendChild(span);// シャドウ DOM を #shadow-dom-host 要素に添付する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;}/* セレクターの引数に一致する場合のみ、 シャドウルートのホストを選択 */:host(.special-custom-element) { font-weight: bold;}構文
:host(<compound-selector>) { /* ... */}例
>シャドウホストの選択的なスタイル設定
以下のスニペットは、host セレクターの例(ライブでも参照)から引用したものです。
この例では、テキストの周りを囲むことができるカスタム要素、<context-span> を使います。
<h1> ホストセレクターの<a href="#"><context-span>例</context-span></a></h1>要素のコンストラクターの中で、style およびspan 要素を作成し、span の中をカスタム要素の中身で埋め、style 要素をいくつかの CSS ルールで埋めます。
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; } は、文書内の<context-span> 要素(この例ではシャドウホスト)のインスタンスでfooter クラスがあるものにスタイルを設定します。このルールを使って<footer> 内の要素のインスタンスに特殊な色を設定しています。
仕様書
| Specification |
|---|
| CSS Shadow Module Level 1> # host-selector> |