:host-context()

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

:host-context()CSS擬似クラス関数で、その中で使用される CSS を含むシャドウ DOM のシャドウホストを選択します。(そのシャドウ DOM の中からカスタム要素を選択することができます)。ただし、関数の引数として指定されたセレクターが DOM 階層の中にあるシャドウホストの祖先に一致する場合に限ります。

言い換えれば、これはカスタム要素、またはそのカスタム要素のシャドウ DOM 内の何らかの要素が、外部 DOM 内の位置、または祖先要素に適用されるクラス/属性に基づいて異なるスタイルが適用できるようにします。

この典型的な使用例として、例えば h1 のような子孫セレクター式を使用して、 <h1> の中にあるカスタム要素のインスタンスのみを選択することができます。例えば、 <body>.dark-theme クラスが適用されたときに異なる文字色を適用するような場合です。

メモ: これは、シャドウ DOM の外で使用しても効果はありません。

試してみましょう

css
/* 指定されたセレクター引数の子孫である場合にのみ、
   シャドウルートホストを選択します。 */
:host-context(h1) {
  font-weight: bold;
}

/* .dark-theme クラスが文書本体に適用されている場合に、
   段落のテキストの色を黒から白に変更します。 */
p {
  color: #000;
}

:host-context(body.dark-theme) p {
  color: #fff;
}

構文

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

シャドウホストの選択的なスタイル設定

以下は、ホストセレクターの例ライブでも見る)から抜粋したものです。

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

html
<h1>
  ホストセレクターの<a href="#"><context-span></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(.footer) { color : red; }" +
  ":host { background: rgb(0 0 0 / 10%); padding: 2px 5px; }";

:host-context(h1) { font-style: italic; } および :host-context(h1):after { content: " - no links in headers!" } のルールは <h1> 内の <context-span> 要素のインスタンス(この例ではシャドウホスト)をスタイル設定します。このデザインでは、カスタム要素が <h1> の中に現れてはいけないことを明確にするために使用しています。

仕様書

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-context()

Legend

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

Full support
Full support
No support
No support
See implementation notes.

関連情報