::slotted()
は CSS の 疑似要素で、 HTML テンプレート内にあるスロットに配置された任意の要素を表します (詳しくはテンプレートとスロットの利用をご覧ください)。
これは shadow DOM 内に配置された CSS の中で使われた時のみ機能します。なお、このセレクターはスロット内に配置されたテキストノードは選択しません。実際の要素のみを対象にします。
/* スロット内に配置された任意の要素を選択 */
::slotted(*) {
font-weight: bold;
}
/* スロット内に配置された <span> 要素を選択 */
::slotted(span) {
font-weight: bold;
}
構文
::slotted( <compound-selector-list> )where
<compound-selector-list> = <compound-selector>#
where
<compound-selector> = [ <type-selector>? <subclass-selector>* [ <pseudo-element-selector> <pseudo-class-selector>* ]* ]!
where
<type-selector> = <wq-name> | <ns-prefix>? '*'
<subclass-selector> = <id-selector> | <class-selector> | <attribute-selector> | <pseudo-class-selector>
<pseudo-element-selector> = ':' <pseudo-class-selector>
<pseudo-class-selector> = ':' <ident-token> | ':' <function-token> <any-value> ')'where
<wq-name> = <ns-prefix>? <ident-token>
<ns-prefix> = [ <ident-token> | '*' ]? |
<id-selector> = <hash-token>
<class-selector> = '.' <ident-token>
<attribute-selector> = '[' <wq-name> ']' | '[' <wq-name> <attr-matcher> [ <string-token> | <ident-token> ] <attr-modifier>? ']'where
<attr-matcher> = [ '~' | | | '^' | '$' | '*' ]? '='
<attr-modifier> = i | s
例
以下のコードの断片は 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>
仕様書
仕様書 | 状態 | 備考 |
---|---|---|
CSS Scoping Module Level 1 ::slotted の定義 |
草案 | 初回定義 |
ブラウザーの対応
BCD tables only load in the browser