html - 调整 HTML 表格大小并强制所有列保留在 View 中

标签 html css html-table

我正在寻找一种简单的解决方案,使表格能够水平缩小,同时保持所有列都在 View 中。随着列缩小,其中的内容应该可以水平滚动。

示例问题:

http://codepen.io/kirkouimet/pen/jybbxK

假设和目标:

  • 我们不知道会有多少列
  • 各列将始终保持在一行上(CSS 空白:nowrap)
  • 理想情况下,解决方案不涉及 JavaScript,只涉及 CSS
  • 如果表格内的文本省略(...),然后当您将鼠标悬停在它上面时,它会展开并且您可以水平滚动它,那就太棒了

Codepen 链接中的代码:

HTML

<table>
    <thead>
        <th>First First First</th>
        <th>Second Second Second</th>
        <th>Third Third Third</th>
        <th>Fourth Fourth Fourth</th>
    </thead>
    <tr>
        <td>First First First</td>
        <td>Second Second Second</td>
        <td>Third Third Third</td>
        <td>Fourth Fourth Fourth</td>
    </tr>
    <tr>
        <td>First First First</td>
        <td>Second Second Second</td>
        <td>Third Third Third</td>
        <td>Fourth Fourth Fourth</td>
    </tr>
    <tr>
        <td>First First First</td>
        <td>Second Second Second</td>
        <td>Third Third Third</td>
        <td>Fourth Fourth Fourth</td>
    </tr>
</table>

CSS

table {
    border-collapse: collapse;
    width: 100%;
}

th, td {
    border: 1px solid #ccc;
    white-space: nowrap;
}

最佳答案

以下 CSS 更改将:

  • 将每个单元格中的文本保留在一行上
  • 当单元格内容比单元格宽时显示省略号
  • 悬停时,省略号将消失并且内容变为可滚动

重要的 CSS 属性是:

table {
  width: 100%;
  table-layout: fixed;
}

th, td {
  white-space: nowrap;
  overflow-x: scroll;
  text-overflow: ellipsis;
}

th:hover,
td:hover {
  text-overflow: clip;
}

这是一个示例,尽管 SO 的布局由于宽度而没有展示滚动功能。有关工作示例,请参阅此 Codepen演示并调整屏幕大小,直到表格单元格变得太窄而无法显示内容。

table {
  border-collapse: collapse;
  width: 100%;
  max-width: 100%;
  table-layout: fixed;
}
th,
td {
  border: 1px solid #ccc;
  white-space: nowrap;
  overflow-x: scroll;
  text-overflow: ellipsis;
}
th:hover,
td:hover {
  text-overflow: clip;
}
<table>
  <thead>
    <th>First First First First First</th>
    <th>Second Second Second Second Second</th>
    <th>Third Third Third Third Third</th>
    <th>Fourth Fourth Fourth Fourth Fourth</th>
  </thead>
  <tr>
    <td>First First First First</td>
    <td>Second Second Second Second</td>
    <td>Third Third Third Third Third</td>
    <td>Fourth Fourth Fourth</td>
  </tr>
  <tr>
    <td>First First First First</td>
    <td>Second Second Second Second</td>
    <td>Third Third Third Third Third</td>
    <td>Fourth Fourth Fourth</td>
  </tr>
  <tr>
    <td>First First First First</td>
    <td>Second Second Second Second</td>
    <td>Third Third Third Third Third</td>
    <td>Fourth Fourth Fourth</td>
  </tr>
</table>

关于html - 调整 HTML 表格大小并强制所有列保留在 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538771/

相关文章:

html - 发生奇怪的 css 溢出效果

jquery - 如何在 ASP.NET 表中创建 thead 和 tbody ?

html - 为什么背景图像在 td 上不起作用?

javascript - 改进下拉菜单的代码 (HTML/CSS/JavaScript)

javascript - html中的 "idd"属性?编辑: can I use Javascript to get an element based off of a custom attribute?

html - 如何制作返回网站横幅

html - 绝对位置 - div 内的 div 不起作用

javascript - Jquery将表格导出到csv隐藏表格单元格

javascript - JSON 数组错误

css - HTML 表单添加需求图片