既存の背景色を活かしたテーブルの交互行デザイン(CSSで自然に濃淡を付ける方法)

CSS、JavaScript
2,695 文字 約 7 分で読めます

テーブルの可読性を上げるために、奇数・偶数行で背景色を変える手法はよく使われます。
しかし、すでに背景色が設定されている場合、単純に nth-child で色を指定するとデザインが崩れてしまうことがあります。

この記事では、既存の背景色を活かしたまま、偶数行を少し濃く見せる方法を紹介します。

よくある問題点

  • 行(tr)に背景色を指定している
  • 特定の列(td:last-child など)にも別の背景色がある
  • 偶数行だけ少し濃くしたいが、色を直接指定したくない

CSSでは「元の色を取得して乗算する」ことはできませんが、見た目として自然に濃く見せる方法はあります。

解決方法の考え方

今回使うのは、疑似要素(::before)と半透明のオーバーレイです。
この方法のメリットは以下です。

  • 既存の背景色を変更しない
  • テーマCSSと衝突しにくい
  • 医療・企業サイトなど落ち着いたデザインに向いている

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::before
  • ::before で半透明レイヤーを重ねる
  • 元の背景色は変更されない
  • どんな色でも自然に「少し濃く」見える
background: rgba(0, 0, 0, 0.04);
  • 数値を小さく → さりげない変化
  • 大きく → コントラストが強くなる
    (0.02〜0.06 あたりが実務で使いやすい)

まとめ

  • CSSでは背景色の「乗算」はできない
  • 疑似要素+半透明オーバーレイで代用できる
  • 既存デザインを壊さずに交互行を表現できる

WordPressテーマや既存CSSがある環境では、
この方法が一番安全で実務向きです。

サンプル

See the Pen surgery-table by kasasagi_kmnmc (@kasasagi_kmnmc) on CodePen.

タイトルとURLをコピーしました