Milk+ea

Weblog Is My Hobby.

擬似クラス:nth-child()について

nth-childという擬似クラスの使い方についての話。
これが使えるようになると「奇数要素だけに適用したい」、「3番目以降の要素にだけ適用したい」といったことができるようになります。

ul li:nth-child(2)  // 2番目の要素に適用
ul li:nth-child(5)  // 5番目の要素に適用
ul li:nth-child(2n+1)  // 奇数番目に適用
ul li:nth-child(odd)  // 奇数番目に適用

ul li:nth-child(3n+1)  // 3の倍数に1足した要素に適用

ul li:nth-child(2n)  // 偶数番目に適用
ul li:nth-child(even)  // 偶数番目に適用

ul li:nth-child(3n)  // 3の倍数に適用

2n+1odd2nevenと同じ結果です。nの前の数の倍数に適用されます。
ちなみに、nは0から始まるので注意です。

// 2番目以前の要素に適用: 0 + 2 = 2, -1 + 2 = 1 
ul li:nth-child(-n+2)

// 3番目以降の要素に適用: 0 + 3 = 3, 1 + 3 = 4, 2 + 3 = 5...
ul li:nth-child(n+3)

HTMLがいじれないときに何か便利ですよ!
あと、「HTMLをスッキリできるんじゃないかな」と思います。