--- title: ':host' slug: 'Web/CSS/:host' tags: - ':host' - CSS - DOM - Layout - Pseudo-class - Reference - Selector - Web - Web Components - shadow - shadow dom - ウェブコンポーネント - シャドウ DOM - セレクター - 擬似クラス translation_of: 'Web/CSS/:host' ---
:host は CSS の 擬似クラスで、その CSS を含むシャドウ DOM のシャドウホストを選択します。 — 言い換えれば、シャドウ DOM の中からカスタム要素を選択できるようにします。
注: これはシャドウ DOM の外で使われたときには効果がありません。
/* シャドウのルートホストを選択 */
:host {
font-weight: bold;
}
:host
以下のスニペットは、 host セレクターの例 (ライブでも参照してください) から取りました。
この例では、テキストの周りを囲むことができる簡単なカスタム要素 — <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 { background: rgba(0,0,0,0.1); padding: 2px 5px; } の規則は、文書中の <context-span> 要素 (このインスタンスのシャドウホスト) のすべてのインスタンスにスタイル付けします。
| 仕様書 | 状態 | 備考 |
|---|---|---|
| {{ SpecName('CSS Scope', '#host-selector', ':host') }} | {{ Spec2('CSS Scope') }} | 初回定義。 |
{{Compat("css.selectors.host")}}