HTMLのtableタグを用いて作成した表の背景色を設定する方法

この記事では、HTMLのtableタグを用いて作成した表の背景色を設定する方法について説明していきます。

backgroundプロパティ

CSSのbackgroundプロパティを用いることでtable要素の背景色を設定することができます。

使用例

HTML
<div class="table-wrapper">
  <table class="table-wrapper__table table">
    <caption class="table__caption">
      キャプション
    </caption>
    <thead class="table__thead thead">
      <tr class="thead__tr">
        <th scope="col" class="thead__th th">テーブルヘッダー</th>
        <th scope="col" class="thead__th th">テーブルヘッダー</th>
      </tr>
    </thead>
    <tbody class="table__tbody tbody">
      <tr class="tbody__tr">
        <td scope="col" class="tbody__td td">テーブルデータ</td>
        <td scope="col" class="tbody__td td">テーブルデータ</td>
      </tr>
      <tr class="tbody__tr">
        <td scope="col" class="tbody__td td">テーブルデータ</td>
        <td scope="col" class="tbody__td td">テーブルデータ</td>
      </tr>
    </tbody>
  </table>
</div>
<!-- /.table-wrapper -->
CSS

こちらでは、thead要素とtbody要素のそれぞれに背景色を設定しています。

.table-wrapper {
  padding: 20px;
}

.table-wrapper__table {
  margin: 0 auto;
}

.table {
  width: 500px;
  max-width: 600px;
  border-collapse: collapse;
}

.table__caption {
  font-weight: 700;
  margin-bottom: 5px;
}

.tbody {
  background-color: ivory;
}

.td {
  border: 1px solid blue;
  padding: 15px 10px;
  text-align: center;
}

.th {
  border: 1px solid blue;
  padding: 15px 10px;
  text-align: center;
}

.thead {
  background-color: aliceblue;
}

上記の例を実行した結果を以下で見ることができます。

実行結果

See the Pen Untitled by Yagi-System (@ihspycal-the-lessful) on CodePen.

まとめ

このように、theadタグやtbodyタグのそれぞれに背景色を指定することで、別々の色を設定することができます。

おすすめの記事

HTMLでtableタグを用いて作成した表の位置を中央寄せにする方法

HTMLでtableタグを用いた表の幅を設定する方法

HTMLでtableタグを用いた表にあるセルを結合する方法

HTMLのtableタグでborderプロパティを設定する方法