テーブルの可読性を上げるために、奇数・偶数行で背景色を変える手法はよく使われます。
しかし、すでに背景色が設定されている場合、単純に nth-child で色を指定するとデザインが崩れてしまうことがあります。
この記事では、既存の背景色を活かしたまま、偶数行を少し濃く見せる方法を紹介します。
よくある問題点
CSSでは「元の色を取得して乗算する」ことはできませんが、見た目として自然に濃く見せる方法はあります。
解決方法の考え方
今回使うのは、疑似要素(::before)と半透明のオーバーレイです。
この方法のメリットは以下です。
HTML(ダミー内容・完全版)
<section id="table-sample">
<h2>実績一覧(ダミー)</h2>
<table>
<tr>
<th>項目</th>
<th>2023年</th>
<th>2024年</th>
</tr>
<tr>
<th>ケースA</th>
<td>120</td>
<td>135</td>
</tr>
<tr>
<th>ケースB</th>
<td>98</td>
<td>110</td>
</tr>
<tr>
<th>ケースC</th>
<td>76</td>
<td>89</td>
</tr>
<tr>
<th>ケースD</th>
<td>54</td>
<td>60</td>
</tr>
</table>
</section>CSS(完全版)
/* セクション全体 */
#table-sample {
max-width: 800px;
margin: 40px auto;
font-family: sans-serif;
}
/* テーブル基本設定 */
#table-sample table {
width: 100%;
border-collapse: collapse;
margin-top: 15px;
}
/* 見出し行 */
#table-sample table tr:first-child th {
background-color: #f2f2f2;
border: none;
font-weight: bold;
}
/* th / td 共通 */
#table-sample table th,
#table-sample table td {
border: 1px solid #ccc;
padding: 14px;
vertical-align: middle;
}
/* th */
#table-sample table th {
text-align: left;
width: 40%;
background-color: #f2f2f2;
}
/* td */
#table-sample table td {
text-align: center;
width: 30%;
}
/* 最後の列だけ別背景色 */
#table-sample table td:last-child {
background-color: #f2f6f5;
}
/* 偶数行の処理(ベース) */
#table-sample table tr:nth-child(even) td {
position: relative;
}
/* 偶数行を少し濃く見せるオーバーレイ */
#table-sample table tr:nth-child(even) td::before {
content: "";
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.04);
pointer-events: none;
}コード解説(要点)
tr:nth-child(even) td::beforebackground: rgba(0, 0, 0, 0.04);まとめ
WordPressテーマや既存CSSがある環境では、
この方法が一番安全で実務向きです。
サンプル
See the Pen surgery-table by kasasagi_kmnmc (@kasasagi_kmnmc) on CodePen.

