やりたいこと
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);
}