是否有一种方法可以将水平滚动条添加到HTML表中?我实际上需要它是可滚动的,垂直和水平取决于表如何增长,但我不能得到任何滚动条出现。


当前回答

首先,做一个显示:块你的表

然后,将overflow-x:设置为auto。

table {
    display: block;
    overflow-x: auto;
    white-space: nowrap;
}

又好又干净。没有多余的格式。

这里有更多涉及的例子,从我的网站上的一个页面滚动表标题。

如果一个关于单元格没有填充整个表的问题,附加以下额外的CSS代码:

table tbody {
    display: table;
    width: 100%;
}

其他回答

用下面的样式将表格包装成DIV:

div.wrapper {
  width: 500px;
  height: 500px;
  overflow: auto;
}

这个答案是我根据之前的解决方案和它的评论得出的,并添加了我自己的一些调整。这在响应式桌子上很适合我。

table {
  display: inline-block;
  overflow-x: auto;
  white-space: nowrap;
  // make fixed table width effected by overflow-x
  max-width: 100%;
  // hide all borders that make rows not filled with the table width
  border: 0;
}
// add missing borders
table td {
  border: 1px solid;
}

我不能让上面的任何解决方案工作。然而,我发现了一个黑客:

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>

这是对Serge Stroobandt的答案的改进,效果非常好。它解决了表没有填充整个页面宽度的问题,如果它有较少的列。

<style> 
 .table_wrapper{
    display: block;
    overflow-x: auto;
    white-space: nowrap;
}
</style>

<div class="table_wrapper">
<table>
...
</table>
</div>

与引导

 <div class="table-responsive">
   <table class="table">
     ...
   </table>
 </div>