首页 > 解决方案 > 达到最大宽度时打破表格单元格内容

问题描述

我有一个这样的 HTML 表:

div {
  width: 100%;
  overflow-x: auto;
}

table {
  white-space: nowrap;
}

td {
  border: 1px solid gray;
  padding: 5px 10px;
  
  min-width: 100px;
  max-width:40vw;
}
<div>
  <table style="width: 100%;">
    <tr>
      <td class="block">1</td>
      <td class="block">A table cell content</td>
      <td class="block">This should be a text that breaks after 200px Lorem ipsum dolor sit amet</td>
      <td class="block">A table cell content</td>
      <td class="block">A table cell content</td>
      <td class="block">A table cell content</td>
      <td class="block">A table cell content</td>
    </tr>
  </table>
</div>

结果:

呈现的 HTML/CSS

问题是,当max-width到达时文本应该换行。我知道white-space: nowrap会导致这个问题,但如果没有达到之前的文本换行max-width

标签: csshtml-tablecss-tables

解决方案


提琴手

td {
  border: 1px solid gray;
  padding: 5px 10px;
  min-width: 100px;
  max-width:40vw;
  white-space: pre-wrap
}

添加或删除white-space: pre-wrap_tdwhite-space: nowraptable

你可以添加span标签td来实现这个输出吗?

span {
  white-space: pre-wrap
}

JsFiddle 2

但是,你已经width:100%在你的table. 我已经像这样在pxwidth:1500px中设置了它。如果您在表格中设置100% 宽度,则剩余的列将在达到其最大宽度之前换行这些文本。

JsFiddle 2 宽度:100%

你可以检查上面的小提琴,我已经设置width:100%table删除了最后两列。现在,冗长的文本列将适应40vw并且剩余的列不会预先包装文本。因此,这也取决于您的父表宽度。


推荐阅读