--- title: ':defined' slug: 'Web/CSS/:defined' tags: - CSS - HTML - Layout - Pseudo-class - Reference - Web - セレクター - 疑似クラス translation_of: 'Web/CSS/:defined' ---
CSS の :defined 疑似クラスは、定義されているすべての要素を表します。これにはブラウザーに組み込まれたすべての標準要素と、 ({{domxref("CustomElementRegistry.define()")}} メソッドを使用して) 定義に成功したカスタム要素が含まれます。
/* 定義されたすべての要素を選択 */
:defined {
font-style: italic;
}
/* 特定の custom 要素のすべてのインスタンスを選択 */
simple-custom:defined {
display: block;
}
{{csssyntax}}
この最初の例は <simple-custom> カスタム要素を定義するスクリプトを含んでいます。
customElements.define('simple-custom',
class extends HTMLElement {
constructor() {
super();
let divElem = document.createElement('div');
divElem.textContent = this.getAttribute('text');
let shadowRoot = this.attachShadow({mode: 'open'})
.appendChild(divElem);
}
})
次に、 <simple-custom> 要素と標準の {{htmlelement("p")}} 要素のインスタンスがある HTML です。
<simple-custom text="Custom element example text"></simple-custom> <p>Standard paragraph example text</p>
それでは CSS です。ここでは、要素の種類に基づいて背景色を定義し、カスタム要素の不透明度を定義済みであるかどうかによって変更し、 :defined セレクターを使用して定義された要素テキストをすべて斜体で表示します。
/* 2つの要素を背景で区別できるようにする */
p {
background: yellow;
}
simple-custom {
display: block;
background: cyan;
}
/* カスタム要素と組み込み要素を両方イタリック体にする */
:defined {
font-style: italic;
}
それから、カスタム要素が定義されていないときには非表示にするルールと、定義されていたらブロックレベル要素として定義して表示します。
simple-custom:not(:defined) {
opacity: 0;
}
simple-custom:defined {
opacity: 0.75;
text-decoration: underline;
}
これは、複雑なカスタム要素があってページの読み込みを待ちたいときに便利です。定義が完了するまで要素のインスタンスを非表示にして、ページ上でスタイル適用前の醜い要素が一瞬現れるのを防ぐことができます。
以上のコードを実行した結果は次の通りです。
{{EmbedLiveSample('Examples')}}
| 仕様書 | 状態 | 備考 |
|---|---|---|
| {{ SpecName('HTML WHATWG', 'semantics-other.html#selector-defined', ':defined') }} | {{ Spec2('HTML WHATWG') }} |
このページの互換性一覧表は構造化データから生成されています。データに協力したいのであれば、 https://github.com/mdn/browser-compat-data をチェックアウトしてプルリクエストを送信してください。
{{Compat("css.selectors.defined")}}