Archive

Archive

nth-childの使い方整理

2026.09.29備忘録

Xの倍数の番号にのみ適用(Xn)

例えば3の倍数の要素に適用する場合

li:nth-child(3n) {  }

Y番目以降に適用(n+Y)

例えば、5番目以降の要素に適用したいとき
以下の場合5・6・7・8・・・番目の要素に適用される
※nは0から始まり5番目から始まる

li:nth-child(n+5) {  }

Y番目までに適用(-n+Y)

5番目までの要素に適用したいとき
以下の場合1~5番目の要素に適用される

li:nth-child(-n+5) {  }

何番目から何個ごとに適用(Xn+Y)

以下、2番目から3個ごとの場合 「2,5,8」が適用される

li:nth-child(3n+2) {  }

N番目以外に適用 :not()

3番目以外に適用したい場合

li:not(:nth-child(3)) {  }

A番目からB番目までに適用 (n+A)(-n+B)

4番目から9番目までの要素に適用

li:nth-child(n+4):nth-child(-n+9) {  }

要素数の個数を限定して適用

要素数が4個のときに、そのすべての要素を適用させるとき

li:first-child:nth-last-child(4), 
li:first-child:nth-last-child(4) ~ li {  }

「li:first-child:nth-last-child(4)」とすることで、最初の要素かつ最後から4番目の要素を指定

「li:first-child:nth-last-child(4) ~ li」は、先ほどの要素から、後ろに続くli要素すべてにスタイルを適用

この方法を使うことで、要素が4個だったときにのみ、スタイルが適用される

N個以上の時に適用

要素数がN個以上のときに、そのすべての要素にスタイルを適用する場合
要素が6個以上のとき
最後から数えて(n+6)番目の要素と、その要素から後ろのli要素全てにスタイルが適用される

li:nth-last-child(n+6),
li:nth-last-child(n+6) ~ li {  }

最新の記事
The Interval Between
the Suffering and Seacow of Continuing
カテゴリー
Classification pizza mocks
for flapping
タグ
What flavor was the roasted
sweet potato you ate yesterday?
ページ上部に戻るスプーン