HTMLのテーブルで縦方向の見出しを作成する方法

HTMLのテーブルで縦方向の見出しを作成する方法

HTMLのテーブルで縦方向の見出しを作成する方法について説明します。
縦方向の見出しは、テーブルの列に対して見出しを設定する場合に使用します。
以下では、HTMLとCSSを別々のファイルに分けて、クラス名とID名には「test-」を付けています。

HTMLファイル (index.html)

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>縦方向の見出しのテーブル</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <table class="test-table">
    <thead>
      <tr>
        <th></th>
        <th class="test-heading">列1</th>
        <th class="test-heading">列2</th>
        <th class="test-heading">列3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th class="test-heading">行1</th>
        <td class="test-cell">データ1-1</td>
        <td class="test-cell">データ1-2</td>
        <td class="test-cell">データ1-3</td>
      </tr>
      <tr>
        <th class="test-heading">行2</th>
        <td class="test-cell">データ2-1</td>
        <td class="test-cell">データ2-2</td>
        <td class="test-cell">データ2-3</td>
      </tr>
      <tr>
        <th class="test-heading">行3</th>
        <td class="test-cell">データ3-1</td>
        <td class="test-cell">データ3-2</td>
        <td class="test-cell">データ3-3</td>
      </tr>
    </tbody>
  </table>
</body>
</html>

CSSファイル (styles.css)

.test-table {
  border-collapse: collapse;
  width: 100%;
}

.test-table th,
.test-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.test-heading {
  background-color: #f2f2f2;
  font-weight: bold;
}

.test-table th:first-child,
.test-table td:first-child {
  writing-mode: vertical-rl;
  text-align: center;
}

説明

1. HTML構造:
HTMLファイルには、テーブルが定義されています。
thead セクションには、横方向の見出しを設定しています。
tbody セクションには、縦方向の見出しとして使う行見出しが含まれています。

2. CSSスタイル:

  • .test-table: テーブル全体のスタイルを設定します。

border-collapse: collapse; により、テーブルのボーダーを一体化しています。

  • .test-table th, .test-table td: テーブルセルに共通のスタイルを設定しています。

ボーダーとパディング、テキストの配置を指定します。

  • .test-heading: 見出しの背景色とフォントの太さを設定します。
  • .test-table th:first-child, .test-table td:first-child: 最初のセル(縦方向の見出し)に対して、writing-mode: vertical-rl; を指定し、縦書きのスタイルを適用しています。

この方法で、テーブル内で縦方向に見出しを表示することができます。
CSSのwriting-modeプロパティを使用することで、見出しを縦方向に回転させることができます。