Web開発

テーブルの行と列をCSSで入れ替える方法

スポンサーリンク

概要

テーブルの行と列(横と縦)をCSSだけで入れ替える方法です。

サンプル

行と列入れ替え前

See the Pen テーブルの行と列の入れ替え前 by take it easy (@take-it-easy) on CodePen.

行と列入れ替え後

See the Pen テーブルの行と列の入れ替え by take it easy (@take-it-easy) on CodePen.

サンプルプログラム

HTML

<table>
  <thead>
    <tr>
      <th>県名</th>
      <th>自治体名</th>
      <th>推定人口</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="center">福岡県</td>
      <td class="center">福岡市</td>
      <td class="right">1,631,409人</td>
    </tr>
    <tr>
      <td class="center">福岡県</td>
      <td class="center">北九州市</td>
      <td class="right">924,143人</td>
    </tr>
    <tr>
      <td class="center">熊本県</td>
      <td class="center">熊本市</td>
      <td class="right">737,850人</td>
    </tr>
    <tr>
      <td class="center">鹿児島県</td>
      <td class="center">鹿児島市</td>
      <td class="right">589,676人</td>
    </tr>
    <tr>
      <td class="center">大分県</td>
      <td class="center">大分市</td>
      <td class="right">474,314人</td>
    </tr>
  </tbody>
</table>

CSS

/**
 * 行と列の入れ替え
 */
table {
  writing-mode: vertical-lr;
  -webkit-writing-mode: vertical-lr;
  -ms-writing-mode: vertical-lr;
}

th,
td {
  writing-mode: horizontal-tb;
  -webkit-writing-mode: horizontal-tb;
  -ms-writing-mode: horizontal-tb;
}

/**
 * テーブルレイアウト
 */
th, td {
  padding: 3px 5px;
}

th {
  background-color: rgba(0, 0, 0, 0.3);
}

td {
  background-color: rgba(0, 0, 0, 0.06);
}

.center {
  text-align: center;
}

.right {
  text-align: right;
}

tableタグに対して「writing-mode: vertical-lr;」(縦書きで左から右へ改行)を、thタグとtdタグに対して「writing-mode: horizontal-tb;」(横書きで上から下へ改行)を設定(1行目〜15行目)することで、テーブルの行と列の入れ替えを行うことができます。

参考

writing-mode - CSS: カスケーディングスタイルシート | MDN

writing-mode – CSS: カスケーディングスタイルシート | MDN

writing-mode は CSS のプロパティで、テキストの行のレイアウトを横書きにするか縦書きにするか、ブロックのフロー方向を左向きにするか右向きにするかを設定します。文書全体に設定する場合は、ルート要素 (HTML 文書の場合は html 要素) に設定してください。

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