LoginSignup
1
0

More than 3 years have passed since last update.

CSSだけで、tableの中にある行(row)の順番を変更して左右反転させる

Posted at

やりたいこと

HTMLで作られたテーブルがあり、これを通常(デフォルト)の設定である「左から右へと行の内容が続いていく」状態をひっくりかえし、順番を入れ替えたい、しかもCSSの記述だけでどうにかしたい!という場面にあり、まぁ出来なくはないのか...と見つけた手法です。

CSSをこう書く

tr (table row)が横向きの行なので、まずこれをtransformで左右反転させます。これだけだと鏡文字になってしまい読めないので、それぞれの構成要素であるtd (table data)を再度左右反転させることで、正常に表示されるようになります。

.reversed table tr {
    transform: scale(-1, 1);
}

.reversed table td {
    transform: scale(-1, 1);
}

上記の要素以外に、th (table header)などががある場合は追記が必要です。table trという具合に子要素で指定しているのは、captionなどはそのままにしておく狙いがあります。

フルサンプル

table.html
<!doctype html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
    <table>
    <caption>通常のテーブル</caption>
        <tr>
            <th>ヘッダー左上</th>     <th>ヘッダー中央</th>     <th>ヘッダー右上</th>
        </tr>
        <tr>
            <td>A1</td>     <td>B1</td>     <td>C1</td>
        </tr>
        <tr>
            <td>A2</td>     <td>B2</td>     <td>C2</td>
        </tr>
    </table>
    <br>
    <div class="container reversed">
    <table>
    <caption>反転しているテーブル</caption>
        <tr>
            <th>ヘッダー左上</th>     <th>ヘッダー中央</th>     <th>ヘッダー右上</th>
        </tr>
        <tr>
            <td>A1</td>     <td>B1</td>     <td>C1</td>
        </tr>
        <tr>
            <td>A2</td>     <td>B2</td>     <td>C2</td>
    </table>
    </div>
</body>
</html>

style.css
.reversed table tr {
    transform: scale(-1, 1);
}

.reversed table th {
    transform: scale(-1, 1);
}

.reversed table td {
    transform: scale(-1, 1);
}

image.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0