E:nth-child(n)は疑似クラスの一種で、 n番目の子となるE要素にスタイルを適用する際に使用できる。 例えば、<table>で使う場合Eがtrならば行のスタイル、thやtdならば列のスタイルを適用することができる。 nの部分には、整数・奇数を表すoddや偶数を表すevenの数式を指定することができる。 例えば、数式で奇数を指定する場合には2n+1、数式で偶数を指定する場合には2n+0となる。
<書式> E:nth-child(n) {プロパティ名:値;}
<適用対象> n番目の子となるE要素
<使用例>
HTMLソース
<body>
<div id="tbl_contener">
<div class="title">
<h3>購入リスト</h3>
</div><!-- title -->
<hr>
<table class="sample">
<tr>
<th>品名</th>
<th>数量</th>
<th>単位</th>
<th>金額(円)</th>
<th>備考</th>
</tr>
<tr>
<td>みかん</td>
<td>10</td>
<td>箱</td>
<td>4,800</td>
<td></td>
</tr>
<tr>
<td>りんご</td>
<td>20</td>
<td>盛</td>
<td>4,300</td>
<td>ふじ</td>
</tr>
<tr>
<td>バナナ</td>
<td>50</td>
<td>房</td>
<td>5,200</td>
<td>フィリピン産</td>
</tr>
<tr>
<td>マスクメロン</td>
<td>8</td>
<td>個</td>
<td>7,000</td>
<td>夕張産</td>
</tr>
<tr>
<td>牛肉</td>
<td>3</td>
<td>kg</td>
<td>5,700</td>
<td>切り落とし</td>
</tr>
<tr>
<td>ジャガイモ</td>
<td>40</td>
<td>個</td>
<td>1,600</td>
<td></td>
</tr>
<tr>
<td>マグロ</td>
<td>2</td>
<td>匹</td>
<td>8,000</td>
<td></td>
</tr>
<tr>
<td>ズワイガニ</td>
<td>15</td>
<td>杯</td>
<td>13,500</td>
<td></td>
</tr>
<tr>
<td>米</td>
<td>10</td>
<td>kg</td>
<td>3,800</td>
<td>新潟産コシヒカリ</td>
</tr>
</table>
</div><!-- tbl_contener -->
</body>
スタイルシート
#tbl_contener {
width:680px;
background: #ffeecc;
padding:5px 0 20px 0;
}
#tbl_contener .title {
width:200px;
margin: 10px auto -10px;
}
#tbl_contener h2 {
line-height:15px;
text-align:center;
}
#tbl_contener table {
width:640px;
border-collapse: collapse;
margin: 0 auto 0;
}
#tbl_contener table th,
#tbl_contener table td {
border:solid 1px;
font-size:13px;
}
/* ヘッダー行のバックグランドカラー */
#tbl_contener table th {
text-align:center;
background-color:#ffffcc;
}
/* 列幅とテキストの配置 */
#tbl_contener table td:nth-child(1) { width:180px; text-align:left; padding:0 3px; }
#tbl_contener table td:nth-child(2) { width:70px; text-align:right; padding:0 3px; }
#tbl_contener table td:nth-child(3) { width:80px; text-align:center; }
#tbl_contener table td:nth-child(4) { width:90px; text-align:right; padding:0 3px; }
#tbl_contener table td:nth-child(5) { width:190px; text-align:left; padding:0 3px; }
/* 奇数行のバックグランドカラー */
#tbl_contener .sample tr:nth-child(2n+1) td {
background-color:#f3f3f3;
}
/* 偶数行のバックグランドカラー */
#tbl_contener .sample tr:nth-child(2n+0) td {
background-color:#ffffff;
}
/* セルが空の場合はテキストの配置を中央にする */
#tbl_contener table td:empty {
text-align:center !important;
}
/* セルが空の場合は"-"を挿入 */
#tbl_contener table td:empty:before {
content: "-";
}
ブラウザ上の表示
購入リスト
| 品名 | 数量 | 単位 | 金額(円) | 備考 |
|---|---|---|---|---|
| みかん | 10 | 箱 | 4,800 | |
| りんご | 20 | 盛 | 4,300 | ふじ |
| バナナ | 50 | 房 | 5,200 | フィリピン産 |
| マスクメロン | 8 | 個 | 7,000 | 夕張産 |
| 牛肉 | 3 | kg | 5,700 | 切り落とし |
| ジャガイモ | 40 | 個 | 1,600 | |
| マグロ | 2 | 匹 | 8,000 | |
| ズワイガニ | 15 | 杯 | 13,500 | |
| 米 | 10 | kg | 3,800 | 新潟産コシヒカリ |