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

ここでは、HTMLでtableタグを用いた表の幅を設定する方法を説明していきます。

tableタグとは

tableタグは、HTMLで表をつくるためのタグで、theadタグ・tbodyタグ・trタグ・thタグ・tdタグを内包します。
tableを用いた表の基本構造については、こちらのサイトで説明していますので、よかったらご覧ください。

tableタグのwidth属性

属性とは

HTMLにおける属性とは、HTMLの各要素に付ける何かしらの設定のことです。

tableタグにはwidth属性がありますが、これは非推奨とされています。
こちらのサイト(外部)を参照

上記の理由から、CSSのwidthプロパティを用いて幅を設定することになります。

コーディング例

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

CSS

.table-wrapper {
  padding: 20px;
}

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

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

.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;
}

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

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

実行結果

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

まとめ

このように、CSSのwidthプロパティを用いることで、tableタグを用いた表の幅を設定することができます。