この記事は
nth-child
を使おうとすると毎回????ってなるからまとめたぞ。
よく使うものも含めてぱっと見でわかるようにしたから、tableの指定とかで発狂しそうになる人はたまに見て心を落ち着かせて欲しい。
nth-child
一覧(よく使うやつ)
※数字とかはサンプルで入れてるだけ
nth-childの種類 | 説明 |
---|---|
:only-child | 要素が一つしかない時 |
:first-child | 最初の要素 |
:last-child | 最後の要素 |
:nth-child(odd) | 奇数要素 |
:nth-child(even) | 偶数要素 |
:nth-child(2) | 最初から2番目の要素 |
:nth-last-child(2) | 最後から2番目の要素 |
:nth-child(3n) | 3の倍数ごと(0,3,6,9…)の要素 |
:nth-child(3n+1) | 3の倍数+1ごと(1,4,7,10…)の要素 |
:nth-child(-n+3) | 最初から3番目までの要素 |
:nth-child(n+3) | 最初から3番目以降の要素 |
only-child
,first-child
,last-child
は特に混乱することなく使えると思うので、:nth-child(odd)
から一個ずつ見ていく。
実際に使ってみる
nth-child(odd)
奇数なので、1,3,5…という風に一個飛ばしで指定される。
See the Pen
:nth-child(odd) by mame_hashbill (@mayu-mameuda)
on CodePen.
:nth-child(even)
偶数なので、2,4,6…という風に一個飛ばしで指定される。
See the Pen
:nth-child(even) by mame_hashbill (@mayu-mameuda)
on CodePen.
:nth-child(2)
今回は括弧内の数字を2としているけど、もちろん3でも4でもOK。
今回は2なので、最初から数えて2行目に色がつく。
See the Pen
:nth-child(2) by mame_hashbill (@mayu-mameuda)
on CodePen.
:nth-last-child(2)
今回は括弧内の数字を2としているけど、もちろん3でも4でもOK。
今回は2なので、最後から数えて2行目に色がつく。
See the Pen
:nth-last-child(2) by mame_hashbill (@mayu-mameuda)
on CodePen.
:nth-child(3n)
今回は括弧内の数字を3としているけど、もちろん4でも5でもOK。
今回は3の倍数3,6,9…という風に色がついてくぞ。
See the Pen :nth-child(3n) by mame_hashbill (@mayu-mameuda) on CodePen.
:nth-child(3n+1)
今回は括弧内の数字を3としているけど、もちろん4でも5でもOK。
今回は3の倍数なので、3×0+1=1,3×1+1=4,3×2+1=7…という風に色がついていくぞ。
ちなみに:nth-child(3n+2)
とすると、
3×0+2=2,3×1+2=5,3×2+2=8…という風に色がついていく。ぱっと見わからんけどまぁ計算すればわかるな。
See the Pen
:nth-child(3n+1) by mame_hashbill (@mayu-mameuda)
on CodePen.
:nth-child(-n+3)
今回は括弧内の数字を+3としているけど、もちろん+4でも+5でもOK。
今回は最初から3番目までの要素が指定される。
でも私はなんで-n
なのかよくわからん。なんで・・・?教えて詳しいひと・・・・
-0+3=3,-1+3=2,-2+3=1となるけど、なんでここで計算が止まるんだろうか。。
See the Pen WNQwzYj by mame_hashbill (@mayu-mameuda) on CodePen.
:nth-child(n+3)
今回は括弧内の数字を+3としているけど、もちろん+4でも+5でもOK。
今回は最後から3番目以降の要素が全て指定される。
これは0+3=3,1+3=4…という風に増えていって、行がなくなったら計算が止まる仕組みなのかね。
See the Pen
:nth-child(n+3) by mame_hashbill (@mayu-mameuda)
on CodePen.
おわりに
childがゲシュタルト崩壊してきた