LoginSignup
3
6

More than 5 years have passed since last update.

ヘッダーが1列目にあるテーブルを作る方法

Posted at

通常htmlでテーブルを作ると以下のような形になる。
<コード>

table.html
<table>
  <thead>
    <tr>
     <th>ヘッダーその①</th>
     <th>ヘッダーその②</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

<表示>

ヘッダーその① ヘッダーその②

でもヘッダーを1行目ではなくこんな感じで1列目にしたい事はわりとあると思う。

ヘッダーその①
ヘッダーその②

それを素直にやろうとすると以下のようなコードになる

table2.html
<table>
  <tr>
    <th>ヘッダーその①</th>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <th>ヘッダーその②</th>
    <td></td>
    <td></td>
  </tr>
</table>

これでも良いのだけど、
個人的にすごい見づらいなぁと思ったので、htmlはそのままにCSSでどうにか出来ないかと考えた。
で、こねこねした結果がこちら。

table3.html
<!-- これはそのまま -->
<table>
  <thead>
    <tr>
      <th>ヘッダーその①</th>
      <th>ヘッダーその②</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>
table.css
thead  {
  float: left;
}
tbody  {
  display: inline-block;
}
thead th  {
  display: block;
}
tbody td  {
  display: block;
}
tbody tr{
  display: inline-block;
}

するとこんな感じになる。
https://jsfiddle.net/85eqhjn6/

一応出来たが、もっと上手い方法がある気がする。
CSS苦手なので頑張る。

以上

3
6
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
3
6