问题
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-block
s 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>
table
shouldn't be displayed as block, if it not necessary for your other layout- I've added
white-space: nowrap
to prevent line wrapping - I've displayed
tbody
andthead
asinline-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