【HTML/CSS】何番目の要素を指定するnth-childの使い方
※本ページのリンクにはプロモーションが含まれています。

こんにちは、Ryohei(@ityryohei)です!
CSSでスタイルを定義する際にHTMLの何番目の要素を指定する、というのはリストやテーブルを作成する際によく利用しますが、毎回を忘れてしまうため良く使う値をまとめてみました!
共通のHTML
以下、共通のHTMLになります。こちらを使ってある番号の要素に異なる装飾を適用させたいと思います!
HTML
<ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul>
何番目の要素
リストの何番目の要素を指定して、スタイルを適用します。以下では3番目にある要素を指定しています。

CSS
li:nth-child( 3 ) { /* CSS */ }
何番目までの要素
ある番号までの要素をすべて指定します。以下では1 ~ 3番目までの要素を指定しています。

CSS
li:nth-child( -n + 3 ) { /* CSS */ }
何番目以降の要素
ある番号以降の要素をすべて指定します。以下では3番目以降の要素をすべて指定しています。

CSS
li:nth-child( n + 3 ) { /* CSS */ }
指定した数字の倍数の要素
指定した値の倍数の要素を指定します。以下では2の倍数の要素をすべて指定しています。

CSS
li:nth-child( 2n ) { /* CSS */ }
奇数番目の要素
奇数番目にある要素を指定します。

CSS
li:nth-child( odd ) { /* CSS */ }
偶数番目の要素
偶数番目にある要素を指定します。

CSS
li:nth-child( even ) { /* CSS */ }