
CSS3から追加された【nth-child】。
このCSS3セレクタを使用する方法を紹介します。
CSSにて奇数行のみや偶数行のみ背景色を変更したり、最後の要素のみボーダーを追加したりする際に使用する本当に便利です。
奇数の要素に適用
td:nth-child(odd){
background: #eee;
}
偶数の要素に適用
td:nth-child(even){
background: #eee;
}
最初の要素に適用
td:first-child{
background: #eee;
}
最後の要素に適用
td:last-child{
background: #eee;
}
5番目の要素に適用
td:nth-child(5){
background: #eee;
}
最初から4番目までの要素に適用
td:nth-child(-n+4){
background: #eee;
}
5番目以降の要素に適用
td:nth-child(n+5){
background: #eee;
}
最後から4番目の要素に適用
td:nth-last-child(4){
background: #eee;
}
最後から4番目以降の要素に適用
td:nth-last-child(-n+4){
background: #eee;
}
最後から4番目以前の要素に適用
td:nth-last-child(n+4){
background: #eee;
}
3の倍数の要素に適用
td:nth-child(3n){
background: #eee;
}
3の倍数に1を足した要素に適用
td:nth-child(3n+1){
background: #eee;
}
使い慣れると非常に便利なセレクタです。
IE8以前には対応していないのが非常に残念です。
コメント
[…] 情報源: 偶数行や奇数行などだけを指定できるCSS3セレクタ | ビジネスニュースで気になる記事を紹介。ラブリーラブリー […]