是否有一种方法可以将水平滚动条添加到HTML表中?我实际上需要它是可滚动的,垂直和水平取决于表如何增长,但我不能得到任何滚动条出现。
当前回答
为此使用CSS属性“overflow”。
简短的总结:
overflow: visible|hidden|scroll|auto|initial|inherit;
e.g.
table {
overflow: scroll;
}
其他回答
我不能让上面的任何解决方案工作。然而,我发现了一个黑客:
body { background-color: #ccc; } .container { width: 300px; background-color: white; } table { width: 100%; border-collapse: collapse; } td { border: 1px solid black; } /* try removing the "hack" below to see how the table overflows the .body */ .hack1 { display: table; table-layout: fixed; width: 100%; } .hack2 { display: table-cell; overflow-x: auto; width: 100%; } <div class="container"> <div class="hack1"> <div class="hack2"> <table> <tr> <td>table or other arbitrary content</td> <td>that will cause your page to stretch</td> </tr> <tr> <td>uncontrollably</td> <td>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</td> </tr> </table> </div> </div> </div>
我尝试了以上所有的解决方案,但都有一些问题。
如果我们添加display: 'block'到表格中,单元格不会占用整个宽度。 如果我们将它添加到表包装器中,你的自定义表头,如搜索,过滤器等也会滚动,这看起来很糟糕。
我能够通过将overflow-x: auto添加到表的主体包装器来实现预期的行为。
单元格采用全宽度,即使列较少,滚动条也会根据需要自动出现。
首先,做一个显示:块你的表
然后,将overflow-x:设置为auto。
table {
display: block;
overflow-x: auto;
white-space: nowrap;
}
又好又干净。没有多余的格式。
这里有更多涉及的例子,从我的网站上的一个页面滚动表标题。
如果一个关于单元格没有填充整个表的问题,附加以下额外的CSS代码:
table tbody {
display: table;
width: 100%;
}
为div元素添加标签表,style="overflow-x:auto"
<div style="overflow-x:auto">
<table class="table table-bordered">
<thead>
<tr>
<th><b>Name</b></th>
<th><b>Username</b></th>
<th><b>Email</b></th>
<th><b>Avatar</b></th>
<th><b>Status</b></th>
<th><b>Action</b></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
我也遇到了同样的问题。我发现了下面的解决方案,它只在Chrome v31中测试过:
table {
table-layout: fixed;
}
tbody {
display: block;
overflow: scroll;
}