CSS3の擬似クラスを使うとセレクタを柔軟に指定することができます。
- x番目の要素 -
:nth-of-type(x)
- x番目以降の要素 -
nth-of-type(n+x)
- 奇数の要素 -
:nth-of-type(odd)
nth-of-type(2n+1)
- 偶数の要素 -
:nth-of-type(even)
:nth-of-type(2n)
- 最初の要素 -
:first-of-type
- 最初の要素以外の要素 -
:not(:first-of-type)
:nth-of-type(n+2)
- 最初から数えてx番目までの要素 -
:nth-of-type(-n+x)
- 最後の要素 -
:last-of-type
- 最後の要素以外 -
:not(:last-of-type)
- 最後から数えてx番目の要素 -
:nth-last-of-type(x)
- 最後の要素でなおかつ奇数の要素 -
:nth-of-type(odd):last-of-type
- 最初の子要素 -
> :first-child
- 最後の子要素 -
> :last-child
- あるクラス名がfooで始まる要素のx番目 -
> [class^="foo"]:nth-child(x)
CSS3の擬似クラスを使う場合はnth-child
のような-child
ではなく、nth-of-type
のようなof-type
を使います。-child
は親要素から見た子要素を要素のタイプに関係なく数えるので、HTMLの構造によっては期待どおりにならないことがあります。