How to change a transposed table to make it horizontally scrollable?

别说谁变了你拦得住时间么 提交于 2019-12-05 18:39:13

Try the combination of inline-blocks and nowrap:

table { border-collapse: collapse; white-space: nowrap; }
tr { display: block; float: left; }
th, td { display: block; border: 1px solid black; }
tbody, thead { display: inline-block; }

tbody {
  width: 300px;
  overflow-y: hidden;
  overflow-x: auto;
}
<table>
<thead>
  <tr>
      <th>name</th>
      <th>number</th>
  </tr>
</thead>
<tbody>
  <tr>
      <td>James Bond</td>
      <td>007</td>
  </tr>
  <tr>
      <td>Lucipher</td>
      <td>666</td>
  </tr>
  <tr>
      <td>Jon Snow</td>
      <td>998</td>
  </tr>
</tbody>
</table>
  1. table shouldn't be displayed as block, if it not necessary for your other layout
  2. I've added white-space: nowrap to prevent line wrapping
  3. I've displayed tbody and thead as inline-block so now you can manage them like inline elements.

If you would like to scroll the tbody only without thead, it might looks like this:

table { border-collapse: collapse; white-space: nowrap; }
tr { display: inline-block; }
th, td { display: block; border: 1px solid black; }
tbody, thead { display: inline-block; vertical-align: top; }

tbody {
  width: 150px;
  overflow-y: hidden;
  overflow-x: auto;
  white-space: nowrap;
}
tbody tr { margin-right: -5px;}
<table>
<thead>
  <tr>
      <th>name</th>
      <th>number</th>
  </tr>
</thead>
<tbody>
  <tr>
      <td>James Bond</td>
      <td>007</td>
  </tr>
  <tr>
      <td>Lucipher</td>
      <td>666</td>
  </tr>
  <tr>
      <td>Jon Snow</td>
      <td>998</td>
  </tr>
</tbody>
</table>

You can think about blocks layout instead. In fact you've already implemented itexcept the HTML what is a bad pattern.

This won't be valid HTML, but you could wrap tbody with a div, then give the div the width and overflow-x property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!