CSSで要素の奇数・偶数を指定(odd/even)
CSSでは:nth-childや:nth-of-typeといった擬似クラスを使うと、並んでいる要素を奇数・偶数で指定することができます。
例えば、
- 1・3・5は背景グレー、2・4・6は背景ホワイトといった表(table)
- 1・3・5は画像を左、2・4・6は画像を右といったレイアウト
といったことがclassを追加することなく可能です。
HTML
<table>
<tr><!-- ← 奇数:odd -->
<th>項目</th>
<td>ここに内容が入ります</td>
</tr>
<tr><!-- ← 偶数:even -->
<th>項目</th>
<td>ここに内容が入ります</td>
</tr>
<!-- 以下、省略 -->
</table>
CSS
/* 奇数 */
tr:nth-child(odd) {
background-color: #eee;
}
/* 偶数 */
tr:nth-child(even) {
background-color: #fff;
}
実行結果
tableのtr、奇数に色を設定
| 奇数 | 奇数 テキストテキスト |
|---|---|
| 偶数 | 偶数 テキストテキスト |
| 奇数 | 奇数 テキストテキスト |
| 偶数 | 偶数 テキストテキスト |
liの偶数に色を設定
- 奇数 リスト
- 偶数 リスト
- 奇数 リスト
- 偶数 リスト