::slotted()
::slotted()
は CSS の 擬似要素で、 HTML テンプレート内にあるスロットに配置された任意の要素を表します (詳しくはテンプレートとスロットの利用をご覧ください)。
これは shadow DOM 内に配置された CSS の中で使われた時のみ機能します。なお、このセレクターはスロット内に配置されたテキストノードは選択しません。実際の要素のみを対象にします。
/* スロット内に配置された任意の要素を選択 */
::slotted(*) {
font-weight: bold;
}
/* スロット内に配置された <span> 要素を選択 */
::slotted(span) {
font-weight: bold;
}
構文
Error: could not find syntax for this item
例
スロット化された要素を強調
以下のコードの断片は slotted-pseudo-element デモから取られたものです (ライブでもご覧ください)。
このデモでは、 3 つのスロットを持つ単純なテンプレートを使用します。
<template id="person-template">
<div>
<h2>Personal ID Card</h2>
<slot name="person-name">NAME MISSING</slot>
<ul>
<li><slot name="person-age">AGE MISSING</slot></li>
<li><slot name="person-occupation">OCCUPATION MISSING</slot></li>
</ul>
</div>
</template>
カスタム要素 — <person-details>
— は以下のように定義されています。
customElements.define('person-details',
class extends HTMLElement {
constructor() {
super();
let template = document.getElementById('person-template');
let templateContent = template.content;
const shadowRoot = this.attachShadow({mode: 'open'});
let style = document.createElement('style');
style.textContent = 'div { padding: 10px; border: 1px solid gray; width: 200px; margin: 10px; }' +
'h2 { margin: 0 0 10px; }' +
'ul { margin: 0; }' +
'p { margin: 10px 0; }' +
'::slotted(*) { color: gray; font-family: sans-serif; } ';
shadowRoot.appendChild(style);
shadowRoot.appendChild(templateContent.cloneNode(true));
}
})
style
要素のコンテンツを埋めると、スロットになるすべての要素を選択し (::slotted(*)
)、それぞれに異なるフォントと色を与えているのが分かるでしょう。これにより、隣のコンテンツが埋まらなかったスロットよりも目立たせることができます。
この要素がページに挿入されると、以下のように見えます。
<person-details>
<p slot="person-name">Dr. Shazaam</p>
<span slot="person-age">Immortal</span>
<span slot="person-occupation">Superhero</span>
</person-details>
仕様書
Specification |
---|
CSS Scoping Module Level 1 # slotted-pseudo |
ブラウザーの互換性
BCD tables only load in the browser