HTML STUDY

テーブルの行背景を一行ごとに変える

CSSでテーブルの行背景を一行ごとにまとめて設定する方法を解説していきます。tr要素をひとつずつ背景を設定するのではなく、奇数行と偶数行に分けてまとめて設定します。

nth-child

テーブルの行背景を交互に変えるにはCSSのtr要素に:nth-child()と記述しカッコの値にodd(奇数)、even(偶数)を与えることによって奇数行と偶数行に分けて背景の色などを設定することができます。

CSSプロパティ解説
tr:nth-child(odd)テーブルの奇数行
tr:nth-child(even)テーブルの偶数行
border-collapseテーブルのセル枠線を重ねる
background-color背景の色
padding内側の余白

HTMLコード記述例

<table class="nth-sample" border="1">
<tr><th>見出し1</th><th>見出し2</th></tr>
<tr><td>行1</td><td>行1</td></tr>
<tr><td>行2</td><行2</td></tr>
<tr><td>行3</td><行3</td></tr>
<tr><td>行4</td><行4</td></tr>
</table>

外部ファイルCSS記述例

@charset "utf-8";

table.nth-sample {
 border-collapse: collapse;
}

table.nth-sample th {
 background-color: #ff9966;
 padding: 5px;
}

table.nth-sample td {
 padding: 5px;
}

table.nth-sample tr:nth-child(odd) {
 background-color: #ffffcc;
}

table.nth-sample tr:nth-child(even) {
 background-color: #ccffff;
}

ブラウザ表示例

見出し1見出し2
行1行1
行2行2
行3行3
行4行4

CSSテーブル 関連記事