【问题标题】:How to horizontally scroll table with nowrap on <th> elements without overflowing into next column?如何在 <th> 元素上使用 nowrap 水平滚动表格而不溢出到下一列?
【发布时间】:2019-01-25 06:52:18
【问题描述】:

我正在创建一个数据表,该表允许水平滚动整个表,同时也只允许垂直滚动&lt;tbody&gt;。我需要包装&lt;td&gt; 标记中的数据,但我不想包装&lt;th&gt; 元素中的文本。

我的问题是我似乎无法让水平滚动条真正工作 - 我的 &lt;th&gt; 标签似乎响应并随着屏幕的宽度缩小,所以我的“空白:nowrap” &lt;th&gt; 元素导致数据溢出到它旁边的列中。

我已经尝试了许多不同的尝试来使它正常工作,但都没有成功。我附上了一个 jsfiddle 和一个我目前正在尝试的例子:

https://jsfiddle.net/vd0wkf47/

当水平收缩浏览器时,我希望&lt;th&gt; 元素在达到文本宽度后停止收缩。那时水平滚动条应该在整个表格中启动。

【问题讨论】:

  • 请使用edit的代码sn-p功能将您的示例代码添加到问题中,而不是在场外。

标签: html css html-table


【解决方案1】:

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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 2021-01-15
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多