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

「HTMLのtableタグでborderを設定する方法」メインビジュアル

ここではHTMLのtableタグで作成した表でborderを設定する方法について説明していきます。

tableタグで表を作る方法

tableタグで表を作るには、theadタグ・tbodyタグ・trタグ・thタグ・tdタグを用います。

theadタグ

theadタグは、表の列のタイトルを構成するタグで、trタグを内包します。

tbodyタグ

tbodyタグは、表の本体部分を構成するタグで、trタグを内包します。

trタグ

trタグは、表の行を定義するタグで、thタグやtdタグを内包します。

thタグ

thタグは、表の行もしくは列のタイトルを定義するタグです。

tdタグ

tdタグは、表のデータを定義するタグです。

tableタグの基本構造

<table>
  <thead>
    <tr>
      <th></th>
      <td></td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th></th>
      <td></td>
    </tr>
  </tbody>
</table>

tableタグ使用例

<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 scope="col" class="thead__th">テーブルヘッダー</th>
        <th scope="col" class="thead__th">テーブルヘッダー</th>
      </tr>
    </thead>
    <tbody class="table__tbody tbody">
      <tr class="tbody__tr">
        <th scope="row" class="tbody__th">テーブルヘッダー</th>
        <td scope="col" class="tbody__td">テーブルデータ</td>
        <td scope="col" class="tbody__td">テーブルデータ</td>
      </tr>
      <tr class="tbody__tr">
        <th scope="row" class="tbody__th">テーブルヘッダー</th>
        <td scope="col" class="tbody__td">テーブルデータ</td>
        <td scope="col" class="tbody__td">テーブルデータ</td>
      </tr>
      <tr class="tbody__tr">
        <th scope="row" class="tbody__th">テーブルヘッダー</th>
        <td scope="col" class="tbody__td">テーブルデータ</td>
        <td scope="col" class="tbody__td">テーブルデータ</td>
      </tr>
    </tbody>
  </table>
</div>
<!-- /.table-wrapper -->

tableタグでborderを設定する方法

tableタグでborderを設定するには、CSSでtheadタグ・tbodyタグ・thタグ・tdタグでborderプロパティを用います。

borderプロパティとは

borderプロパティは、HTML要素の枠線を設定するプロパティです。

borderプロパティ使用例

.table-wrapper {
  padding: 40px;
}

.table {
  width: 100%;
  max-width: 600px;
}

.table__caption {
  font-weight: 700;
}

.thead {
  border-left: 2px solid #000;
  border-top: 2px solid #000;
  border-right: 2px solid #000;
}

.thead__th {
  border-right: 2px solid #000;
  border-bottom: 2px solid #000;
  padding: 15px 10px;
  text-align: center;
}

.tbody {
  border-left: 2px solid #000;
  border-bottom: 2px solid #000;
  border-right: 2px solid #000;
}

.tbody__th {
  border-right: 2px solid #000;
  border-bottom: 1px solid #000;
  padding: 15px 10px;
  text-align: center;
}

.tbody__td {
  border-right: 2px solid #000;
  border-bottom: 1px solid #000;
  padding: 15px 10px;
  text-align: center;
}

出力結果

See the Pen Untitled by 八木康至 (@ihspycal-the-lessful) on CodePen.

まとめ

上記のように、tableタグのtbodyタグとthタグ、tdタグにborderプロパティを指定することで表に枠線を付加することができます。