CSS3セレクタで1行ごとにテーブルに背景色をつける
IE6~8でもCSS3セレクタが利用できるツールの決定版「Selectivizr」 で紹介したようにCSS3セレクタはIE対策も容易なのでぜひお試しください。
サンプル1
ブラウザ | 開 発 |
---|---|
Firefox | Mozilla |
Chrome | |
Internet Explorer | microsoft |
Safari | apple |
Opera | Opera Software |
htmlは非常にシンプルな普通のテーブルです。
html
<table> <tr> <th>ブラウザ</th> <th>開 発</th> </tr> <tr> <td>Firefox</td> <td>Mozilla</td> </tr> <tr> <td>Chrome</td> <td>Google</td> </tr> <tr> <td>Internet Explorer</td> <td>microsoft</td> </tr> <tr> <td>Safari</td> <td>apple</td> </tr> <tr> <td>Opera</td> <td>Opera Software</td> </tr> </table>
次にCSSです。
CSS
table { width: auto; border: 1px solid #B0C4DE; border-collapse: collapse; border-spacing: 0; } th { color: #fff; padding: 5px; border-bottom: 1px solid #B0C4DE; border-left: 1px solid #B0C4DE; background: #4682B4; font-weight: bold; line-height: 120%; text-align: center; } td { padding: 5px; border-bottom: 1px solid #B0C4DE; border-left: 1px solid #B0C4DE; } tr:nth-child(2n+1) { background: #F0FFFF; }
ポイントは最後の「tr:nth-child(2n+1) 」です。以下のように規則に則ってスタイルが適用されます。
tr:nth-child(n) ・・・ n番目のtrに適用
tr:nth-child(odd) ・・・ 奇数番目のtrに適用
tr:nth-child(2n+1) ・・・ 奇数番目のtrに適用
tr:nth-child(even) ・・・ 偶数番目のtrに適用
tr:nth-child(2n) ・・・ 偶数番目のtrに適用
tr:nth-child(3n) ・・・ 3,6,9,12…番目のtrに適用
tr:nth-child(3n+1) ・・・ 1,4,7,10…番目のtrに適用
tr:nth-child(odd) ・・・ 奇数番目のtrに適用
tr:nth-child(2n+1) ・・・ 奇数番目のtrに適用
tr:nth-child(even) ・・・ 偶数番目のtrに適用
tr:nth-child(2n) ・・・ 偶数番目のtrに適用
tr:nth-child(3n) ・・・ 3,6,9,12…番目のtrに適用
tr:nth-child(3n+1) ・・・ 1,4,7,10…番目のtrに適用
ということで今回の場合偶数行のみ背景色をつけています。
サンプル2
「:nth-child(n)」を使用例をもう1つ。縦に長いテーブルで5行ごとに線を太くして見やすくしてみます。
1 | 5行ごとに線が太くなっています |
---|---|
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
11 | |
12 | |
13 |
htmlは先ほど同様、基本的なテーブルです。7行目以降省略しています。
html
<table> <tr> <th>1</th> <td>5行ごとに線が太くなっています</td> </tr> <tr> <th>2</th> <td> </td> </tr> <tr> <th>3</th> <td> </td> </tr> <tr> <th>4</th> <td> </td> </tr> <tr> <th>5</th> <td> </td> </tr> <tr> <th>6</th> <td> </td> </tr> </table>
次にCSSです。
CSS
table { width: auto; border: 1px solid #B0C4DE; border-collapse: collapse; border-spacing: 0; } th { color: #fff; padding: 5px; border-bottom: 1px solid #B0C4DE; border-left: 1px solid #B0C4DE; background: #4682B4; font-weight: bold; line-height: 120%; text-align: center; } td { padding: 5px; border-bottom: 1px solid #B0C4DE; border-left: 1px solid #B0C4DE; } tr:nth-child(2n+1) { background: #F0FFFF; } tr:nth-child(5n) { border-bottom: 2px solid #B0C4DE; }
偶数行で背景色を指定し、5行ごとに線を太くしています。
ちょっとしたことですが、あるのとないのではかなり印象は違いますね。
フィードやTwitterで最新情報をチェック

良ければ、私のサイトの登録手順ページの伝わりやすい画像+説明方法を
教えてもらえませんか?