CSS入門 | CSSセレクター | 構造疑似クラス

構造疑似クラス

構造疑似クラスを使用すると、HTML要素の階層構造で特定位置にある要素を選択できる。

CSSで使用できる構造疑似クラスは次のとおりである。

疑似クラス 説明
:first-child すべての子要素の中で最初に位置する子要素をすべて選択する。
:last-child すべての子要素の中で最後に位置する子要素をすべて選択する。
:nth-child すべての子要素の中で前からn番目に位置する子要素をすべて選択する。
:nth-last-child すべての子要素の中で後ろからn番目に位置する子要素をすべて選択する。
:first-of-type すべての子要素の中で最初に登場する特定タイプの要素をすべて選択する。
:last-of-type すべての子要素の中で最後に登場する特定タイプの要素をすべて選択する。
:nth-of-type すべての子要素の中でn番目に登場する特定タイプの要素をすべて選択する。
:nth-last-of-type すべての子要素の中で後ろからn番目に登場する特定タイプの要素をすべて選択する。
:only-child 子要素を1つだけ持つ要素の子要素をすべて選択する。
:only-of-type 子要素として特定タイプの要素を1つだけ持つ要素の子要素をすべて選択する。
:empty 子要素をまったく持たない要素をすべて選択する。
:root 文書のroot要素を選択する。

:first-child

:first-childは、すべての子要素の中で最初に位置する子要素をすべて選択する。

<style>
    p:first-child { color: red; font-weight: bold; }
</style>

:last-child

:last-childは、すべての子要素の中で最後に位置する子要素をすべて選択する。

<style>
    p:last-child { color: red; font-weight: bold; }
</style>

:nth-child

:nth-childは、すべての子要素の中で前からn番目に位置する子要素をすべて選択する。

<style>
    p:nth-child(2n) { color: red; font-weight: bold; }
</style>

:nth-last-child

:nth-last-childは、すべての子要素の中で後ろからn番目に位置する子要素をすべて選択する。

<style>
    p:nth-last-child(3n) { color: red; font-weight: bold; }
</style>

:first-of-type

:first-of-typeは、すべての子要素の中で最初に登場する特定タイプの要素をすべて選択する。

<style>
    p:first-of-type { color: red; font-weight: bold; }
</style>

:last-of-type

:last-of-typeは、すべての子要素の中で最後に登場する特定タイプの要素をすべて選択する。

<style>
    p:last-of-type { color: red; font-weight: bold; }
</style>

:nth-of-type

:nth-of-typeは、すべての子要素の中でn番目に登場する特定タイプの要素をすべて選択する。

<style>
    p:nth-of-type(2n) { color: red; font-weight: bold; }
</style>

:nth-last-of-type

:nth-last-of-typeは、すべての子要素の中で後ろからn番目に登場する特定タイプの要素をすべて選択する。

<style>
    p:nth-last-of-type(2n+1) { color: red; font-weight: bold; }
</style>

:only-child

:only-childは、子要素を1つだけ持つ要素の子要素をすべて選択する。

<style>
    p:only-child { color: red; font-weight: bold; }
</style>

:only-of-type

:only-of-typeは、子要素として特定タイプの要素を1つだけ持つ要素の子要素をすべて選択する。

<style>
    p:only-of-type { color: red; font-weight: bold; }
</style>

:empty

:emptyは、子要素をまったく持たない要素をすべて選択する。

<style>
    p:empty { width: 300px; height: 20px; background: red; }
</style>

:root

:rootは、該当文書のroot要素を選択する。

<style>
    :root { background: red; }
</style>

HTML文書でroot要素は常にhtml要素である。