[英]How to horizontally scroll table with nowrap on <th> elements without overflowing into next column?
I'm working to create a data table that allows for horizontal scrolling of the entire table, while also allowing vertical scrolling of only the <tbody>
.我正在努力创建一个数据表,它允许整个表的水平滚动,同时还允许仅<tbody>
垂直滚动。 I need the data in the <td>
tags to wrap, but I do not want wrapping on the text in the <th>
elements.我需要<td>
标签中的数据来换行,但我不想在<th>
元素中的文本上换行。
My problem is that I can't seem to get the horizontal scrollbar to actually work - my <th>
tags seem to be responsive and shrink along with the width of the screen, so my "white-space: nowrap" on the <th>
elements causes the data to spill out into the column beside it.我的问题是我似乎无法让水平滚动条实际工作 - 我的<th>
标签似乎响应并随着屏幕宽度缩小,所以我在<th>
> 上的“white-space: nowrap” <th>
元素导致数据溢出到它旁边的列中。
I've tried a number of different attempts to get this working with no luck.我已经尝试了许多不同的尝试来让这个工作没有运气。 I'm attaching a jsfiddle with an example of what I'm currently trying:我正在附上一个 jsfiddle,并附上我目前正在尝试的示例:
https://jsfiddle.net/vd0wkf47/ https://jsfiddle.net/vd0wkf47/
When horizontally shrinking the browser, I want the <th>
elements to stop shrinking once it reaches the text width.当水平缩小浏览器时,我希望<th>
元素在达到文本宽度后停止缩小。 That's when the horizontal scrollbar should kick in for the entire table.这就是水平滚动条应该在整个表格中起作用的时候。
Set a width on the th
elements and set overflow
to auto
:在第th
元素上设置宽度并将overflow
设置为auto
:
th {
white-space: nowrap;
width: calc(50% - .5em); /* half of your thead width */
display: inline-block;
overflow: auto;
-webkit-overflow-scrolling: touch; /* smooth scroll on iOS */
}
table { border-collapse: collapse; width: 100%; } table, th, td { border: 1px solid black; } thead, tr { display:table; width:100%; table-layout:fixed; } thead { width: calc( 100% - 1em ); } th { white-space: nowrap; width: calc(50% - .5em); display: inline-block; overflow: auto; } tbody { max-height:100px; display:block; overflow-y: scroll; overflow-x: hidden; } td { overflow-wrap: } .table-wrapper { overflow-x: scroll; overflow-y: hidden; }
<div class="table-wrapper"> <table> <thead> <th>A Long Long Long Header A Long Long Long Header</th> <th>Second Header</th> </thead> <tbody> <tr> <td>Data 1</td> <td>Data 2</td> </tr> <tr> <td>Long Long Longggggggggg Data</td> <td>Data 2</td> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> <tr> <td>Long Long Longggggggggg Data</td> <td>Data 2</td> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> </tbody> </table> </div>
https://jsfiddle.net/u5fpc160/1/ https://jsfiddle.net/u5fpc160/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.