指定の子要素に対してスタイルを適用 nth-child - CSS
nth-childを使うことで「2番目だけ」とか「5番目以降」にスタイルを適用するみたいなのができるようになる。
偶数番目の要素だけとか!!
nth-childはセレクタに追加して条件を指定する擬似クラスのひとつで、子要素のn番目(nth)にスタイルを適用させることができます。 多数の項目がある表で、交互に背景色を設定し見やすくしたい時などに役立ちます。
擬似クラスを覚えよう!CSSのnth-childの使い方 | TechAcademyマガジン
書き方
セレクタ:nth-child(値) {...}
指定できる値の種類は以下の通り
値 | 説明 |
---|---|
2n かeven |
偶数番目の要素 |
2n+1 かodd |
奇数番目の要素 |
a |
a番目の要素 |
n+b |
b番目以降の要素(bを含む) |
-n+b |
b番目以前の要素(bを含む) |
an |
aの倍数の要素 |
※ a
とb
は整数
偶数 番目に適用
2n
かeven
を指定する
.content:nth-child(2n) {...} .content:nth-child(even) {...}
偶数番目の背景色を水色に変える
See the Pen 偶数番目にスタイルを適用 by tamago (@tamago324) on CodePen.
奇数 番目に適用
2n+1
かodd
を指定する
.content:nth-child(2n+1) {...} .content:nth-child(odd) {...}
奇数番目の背景色を水色に変える
See the Pen 奇数番目にスタイルを適用 by tamago (@tamago324) on CodePen.
n番目の要素に適用
n番目だけに適用したい場合、その「数値」を指定する
.content:nth-child(数値) {...}
3番目だけ背景色を水色に変える
.content:nth-child(3) {...}
See the Pen 3番目だけにスタイルを適用 by tamago (@tamago324) on CodePen.
nを指定すると???
n
を指定すると、全てという意味になる
たまたま、n
だけ記述したら全てに適用されて発見した
.content:nth-child(n) {...}
n番目以降の要素に適用
n+数値
とすることで、指定した数値以降の要素にスタイルが適用される
.content:nth-child(n+数値) {...}
3番目以降の要素の背景色を水色に変える
.content:nth-child(n+3) {...}
See the Pen n番目以降の要素にスタイルを適用する by tamago (@tamago324) on CodePen.
n番目以前の要素に適用
-n+数値
とすることで、指定した数値以前の要素にスタイルが適用される
.content:nth-child(-n+数値) {...}
3番目以前の要素の背景色を水色に変える
.content:nth-child(-n+3) {...}
See the Pen QrGMPy by tamago (@tamago324) on CodePen.
応用?
:nth-child()
をつな出て書くことで範囲指定することができる
.content:nth-child(値):nth-child(値) {...}
3番目から5番目まで背景色を水色に変える
.content:nth-child(n+3):nth-child(-n+5) {...}
See the Pen 3から5番目までスタイルを適用 by tamago (@tamago324) on CodePen.