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


当前回答

为此使用CSS属性“overflow”。

简短的总结:

overflow: visible|hidden|scroll|auto|initial|inherit;

e.g.

table {
    overflow: scroll;
}

其他回答

为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>

如前所述,使用display:block;在桌子上是坏的。我尝试了这个帖子中的大多数答案,没有一个像我想要的那样有效。如果你的HTML是这样结构的:

<div>
  <table>
    <tbody>

你想让父div水平滚动,你可以试试下面的方法:

.text-left {text-align:left;} /* Ignore */ .x-auto { overflow-x: auto; } .table { text-align: left; table-layout: fixed; width: 100%; white-space: nowrap; } .table tbody { display: table; width: 100%; } <div class="x-auto"> <table class="table text-left"> <tbody> <tr> <th>Head1</th> <th>Head2</th> </tr> <tr> <td>Some short text!</td> <td>Some really long text, like really really really really really really really really really really really really long!</td> </tr> </tbody> </table> </div>

.wrapper {
  width: 0;
  min-width: 100%; //width 0, but min-width 100?? yes, I know...
  overflow: auto;
}
<div class="wrapper">
  <table></table>
</div>

表可以有任何宽度。我通常使用100%或max-content作为表。

我尝试了以上所有的解决方案,但都有一些问题。

如果我们添加display: 'block'到表格中,单元格不会占用整个宽度。 如果我们将它添加到表包装器中,你的自定义表头,如搜索,过滤器等也会滚动,这看起来很糟糕。

我能够通过将overflow-x: auto添加到表的主体包装器来实现预期的行为。

单元格采用全宽度,即使列较少,滚动条也会根据需要自动出现。

与引导

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