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

放肆的年华 提交于 2019-12-07 15:04:31

问题


I am making a table for products comparison. It's a table with vertical rows, a header at the left side and two or more product descriptions in vertical rows inside table body. It should be horizontally scrollable in case if user chooses a lot of products.

I have used CSS from this answer to transpose a table (i.e. make vertical rows). And now I can't manage to add a horizontal scrollbar inside tbody in case if table exceeds the predefined width. I am looking for something similar to this question but applied to my transposed table.

Here's what I have now: JSFiddle and here's what happens when I limit the table width to 200px:


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/43442893/how-to-change-a-transposed-table-to-make-it-horizontally-scrollable

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