--- title: ':host-context()' slug: 'Web/CSS/:host-context()' tags: - ':host-context()' - CSS - Experimental - Layout - Pseudo-class - Reference - Selector - Web translation_of: 'Web/CSS/:host-context()' ---
:host-context() は CSS の擬似クラス関数で、内部で使用される CSS を含むシャドウ DOM のシャドウホストを選択します (そのため、シャドウ DOM の中のカスタム要素を選択することができます)。 — しかし、関数の引数として与えられたセレクターがシャドウホストの祖先に一致した場合のみです。
言い換えれば、これによってカスタム要素やそのカスタム要素のシャドウ DOM 内のものは、外部 DOM 内の位置や、祖先要素に適用されたクラスや属性に基づいて、異なるスタイルを適用することができます。
典型的な使い方としては、子孫のセレクター式 (例えば h1) を使って、 <h1> の中にあるカスタム要素のインスタンスのみを選択することができます。もう一つの典型的な使用法は、内部要素が任意の子孫要素のクラスや属性に反応するようにすることです。例えば、 .dark-theme クラスが <body> に適用されたときに、異なるテキスト色を適用することができます。
注: これはシャドウ DOM の外で使用した場合、効果がありません。
/* Selects a shadow root host, only if it is
a descendant of the selector argument given */
:host-context(h1) {
font-weight: bold;
}
:host-context(main article) {
font-weight: bold;
}
/* Changes paragraph text color from black to white when
a .dark-theme class is applied to the document body */
p {
color: #000;
}
:host-context(body.dark-theme) p {
color: #fff;
}
以下のスニペットは host-selectors example から取ったものです。 (ライブ版もあります).
この例には、単純なカスタム要素 — <context-span> — があり、テキストを囲むことができます。
<h1>Host selectors <a href="#"><context-span>example</context-span></a></h1>
要素のコンストラクターの中で、 style および span 要素を生成し、 span の中をカスタム要素の内容で埋め、 style 要素をいくつかの CSS 規則で埋めます。
let style = document.createElement('style');
let 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: rgba(0,0,0,0.1); padding: 2px 5px; }';
:host-context(h1) { font-style: italic; } および :host-context(h1):after { content: " - no links in headers!" } の規則は <h1> の中にある <context-span> 要素 (このインスタンスのシャドウホスト) のインスタンスをスタイル付けします。これは設計上、 <h1> 内部にカスタム要素が現れるべきではないことを明確にするために使用しています。
| 仕様書 | 状態 | 備考 |
|---|---|---|
| {{ SpecName('CSS Scope', '#host-selector', ':host-context()') }} | {{ Spec2('CSS Scope') }} | 初回定義 |
{{Compat("css.selectors.host-context")}}