擬似クラス
CSS の擬似クラスは、セレクターに付加するキーワードであり、選択された要素に対して特定の状態を指定します。例えば :hover
擬似クラスで、ユーザーのポインターが当たったときにボタンの色を変更することができます。
/* ユーザーのポインターが当たっているすべてのボタン */
button:hover {
color: blue;
}
擬似クラスにより、文書ツリーのコンテンツに関するものだけでなく、閲覧履歴 (例えば :visited
)、コンテンツの状態 (例えばフォーム要素における :checked
)、マウスポインタの位置 (例えばマウスポインタが要素上にあるかを知ることができる :hover
) といった外的要因との関係についてスタイルを適用することができるようになります。
メモ: 擬似要素は擬似クラスとは対照的に、 pseudo-elements
は要素の特定の部分にスタイルを適用するために使用します。
構文
selector:pseudo-class { property: value; }
通常のクラスと同様に、必要であれば1つのセレクターに複数の擬似クラスを並べることができます。
標準擬似クラスの索引
:active
:any-link
:blank
:checked
:current
(en-US):default
:defined
:dir()
:disabled
:drop
:empty
:enabled
:first
:first-child
:first-of-type
:fullscreen
:future
(en-US):focus
:focus-visible
:focus-within
:has()
:host
:host()
(en-US):host-context()
:hover
:indeterminate
:in-range
:invalid
:is()
:lang()
:last-child
:last-of-type
:left
:link
:local-link
(en-US):not()
:nth-child()
:nth-col()
(en-US):nth-last-child()
:nth-last-col()
(en-US):nth-last-of-type()
:nth-of-type()
:only-child
:only-of-type
:optional
:out-of-range
:past
(en-US):placeholder-shown
:read-only
:read-write
:required
:right
:root
:scope
:target
:target-within
(en-US):user-invalid
(en-US):valid
:visited
:where()
仕様書
仕様書 | 状態 | 備考 |
---|---|---|
Fullscreen API | 現行の標準 | :fullscreen を定義。 |
HTML Living Standard | 現行の標準 | いつ特定のセレクターが HTML 要素に一致するのかを定義。 |
Selectors Level 4 | 草案 | :any-link , :blank , :local-link , :scope , :drop , :current , :past , :future , :placeholder-shown , :user-invalid , :nth-col() , :nth-last-col() , :is() and :where() を定義:empty の動作を :-moz-only-whitespace のように変更。Selectors Level 3 および HTML5 で定義された擬似クラスについて、大きな変更はなし (ただし意味論的な意味は引き継いでいません)。 |
HTML5 | 勧告 | 正規の (WHATWG) HTML 仕様書から関連する節を複写。 |
CSS Basic User Interface Module Level 3 | 勧告 | :default , :valid , :invalid , :in-range , :out-of-range , :required , :optional , :read-only , :read-write を定義。ただし意味論的な意味は定義していません。 |
Selectors Level 3 | 勧告 | :target , :root , :nth-child() , :nth-last-of-child() , :nth-of-type() , :nth-last-of-type() , :last-child , :first-of-type , :last-of-type , :only-child , :only-of-type , :empty , :not() を定義。:enabled , :disabled , :checked , :indeterminate の構文を定義。ただし意味論的な意味は定義していません。CSS Level 2 (Revision 1) で定義された擬似クラスについて、大きな変更はなし。 |
CSS Level 2 (Revision 1) | 勧告 | :lang() , :first-child , :hover , :focus を定義。CSS Level 1 で定義された擬似クラスについて、大きな変更はなし。 |
CSS Level 1 | 勧告 | :link , :visited , :active を定義。ただし意味論的な意味は定義していません。 |