cssやjQueryでn番目の要素を指定する疑似クラスnth-of-type()、nth-child()

2017年9月17日

n番目を指定するための便利なクラスnth-○○の使い方一覧

基本

親要素からみた子要素のn番目を指定する
nth-of-typeはタグの種類を限定して数える
nth-childはすべてのタグを数える

  1. <div>
  2. <p>1</p>
  3. <div>2</div> ← div:nth-child(2)
  4. <div>3</div> ← div:nth-of-type(2)
  5. </div>

最初

:first-of-type
:first-child

最後

:last-of-type
:last-child

n番目

:nth-of-type(n)
:nth-child(n)

Xの倍数番目

:nth-of-type(Xn)
:nth-child(Xn)

最後からn番目

:nth-last-of-type(n)
:nth-last-child(n)

X番目以降

:nth-of-type(n + X)
:nth-child(n + X)

X番目まで

:nth-of-type(-n + X)
:nth-child(-n + X)

最後からX個

:nth-last-of-type(-n + X)
:nth-last-child(-n + X)

最後からX番目以前

:nth-last-of-type(n + X)
:nth-last-child(n + X)

1個だけ

:only-of-type
:only-child

Y番目以降Xの倍数

:nth-of-type(n + Y):nth-of-type(Xn)
:nth-child(n + Y):nth-child(Xn)