【问题标题】:How to add an horizontal scrollbar to a table with unfixed width?如何在不固定宽度的表格中添加水平滚动条?
【发布时间】:2017-11-29 05:05:06
【问题描述】:

我想在表格中添加水平滚动条。但是用户可以向表中添加行,因此它的宽度必须改变。一行是 100px 宽度,所以有 10 行,我的表格宽度为 1000px,但包含表格的 div 只有 800px 宽度。如果表格的宽度大于 div 的宽度,我想要表格中的水平滚动条。

<div style="width:800px;overflow:auto;">
    <table>...</table>
</div>

你知道怎么做吗?

【问题讨论】:

    标签: html css scrollbar css-tables


    【解决方案1】:

    您只需添加overflow-x:scroll 即可做到这一点,x 轴上总会有一个滚动条。

    【讨论】:

      【解决方案2】:

      我放上div容器:

      overflow-x: auto;
      white-space: nowrap;
      

      在 div 和 table 上:

      width: -moz-available;
      width: -webkit-fill-available;
      

      简化的html:

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

      我在同一页面上有几张表格,其中一张会比全宽窄,因此会被拉伸。另一个更宽,因此它显示为容器的全宽并具有水平滚动条。

      【讨论】:

      • fill-available 现在称为“stretch”
      【解决方案3】:

      overflow: auto; 添加到您的 div 并为您的表格提供固定宽度 + overflow-x: scroll;

      看看:

      div {
        overflow: auto;
      }
      
      table {
        overflow-x: scroll;
        width: 800px;
      }
      
      th, td {
        width: 100px;
      }
      <div>
          <table>
            <th>1</th>
            <th>2</th>
            <th>3</th>
            <th>4</th>
            <th>5</th>
            <th>6</th>
            <th>7</th>
            <th>8</th>
            <th>9</th>
            <th>10</th>
          </table>
      </div>

      【讨论】:

        【解决方案4】:

        试试这个代码

        div {
          overflow-x: auto;
          width: 800px;
        }
        <div>
          <table border="1">
            <tr>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
              <td>test</td>
            </tr>
        
          </table>
        </div>

        【讨论】:

        • 有 2 个滚动条(1 个用于表格,1 个用于整个内容)。您需要使用 2 个不同的滚动条来完全倒回表格。
        猜你喜欢
        • 2013-07-06
        • 1970-01-01
        • 2018-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        相关资源
        最近更新 更多