【问题标题】:Autoadjust cell width to content in CSS with overflows自动调整单元格宽度以适应 CSS 中溢出的内容
【发布时间】:2017-10-02 18:26:40
【问题描述】:

我有下表,每个单元格中的内容宽度不同。我想要长在 nowrap 和溢出旁边。

我试过这里提到的:Why does overflow:hidden not work in a <td>?

但结果是所有单元格的宽度都相同,我需要单元格调整到内部内容,所以在内容短的单元格(例如复选框一)中没有那么多腰部的空白。

我不能改为应用 div,也不能对每一列应用特定的宽度,因为它是一个动态表格,因此列数和内容可能会发生变化。

¿有什么线索吗?

这是代码。见example at JSfiddle

<html>
  <head>
    <style>
    table {
      width: 100%;
    }
    table td {
      border: 1px solid #ccc;
      max-width: 1px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td>
          <input type="checkbox" />
        </td>
        <td>
          ID001
        </td>
        <td>
          Long-text-I-want-to-overflow-without-making-the-other-columns-wider-Long-text-I-want-to-overflow-without-making-the-other-columns-wider-Long-text-I-want-to-overflow-without-making-the-other-columns-wider-Long-text-I-want-to-overflow-without-making-the-other-columns-wider-
        </td>
      </tr>
    </table>
  </body>
</html>

【问题讨论】:

  • 列的大小除以应用到它的最大宽度。由于您已将所有列的最大宽度设置为 1px,因此列的大小相同,这就是您拥有三个等宽列的原因。如果你的长文本总是在你的最后一列,你可以给它一个更大的尺寸 - 例如jsfiddle.net/qfsoo4wv/2 - 如果复选框在第一个,你可以把它变小:jsfiddle.net/qfsoo4wv/3 但这意味着所有共享大小的列的宽度都相同
  • 谢谢皮特,这正是我的问题,最后一列不会总是最大的,第一列也不会总是放置一个复选框。我认为我没有合适的解决方案:(
  • 我也有同样的情况,你有什么可行的解决方案???

标签: html css html-table overflow


【解决方案1】:

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

table td:nth-of-type(1) {
  width: 20px;
  padding: 5px 0;
}
table td:nth-of-type(2) {
  width: 100px;
}
table td {
  border: 1px solid #ccc;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 5px 10px;
}
<table>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>
      ID001
    </td>
    <td>
      Long-text-I-want-to-overflow-without-making-the-other-columns-wider-Long-text-I-want-to-overflow-without-making-the-other-columns-wider-Long-text-I-want-to-overflow-without-making-the-other-columns-wider-Long-text-I-want-to-overflow-without-making-the-other-columns-wider-
    </td>
  </tr>
</table>

【讨论】:

  • 谢谢,尼克,我已经尝试过了,但正如我所说,我不想为任何列指定特定宽度,因为这些列的内容可能会有所不同。我希望宽度自动调整为内部内容。
  • OP 已明确声明:我不能对每列应用特定宽度,因为它是动态表格
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 2017-03-02
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 2016-03-12
  • 2012-10-13
相关资源
最近更新 更多