设置最大宽度 table

Setting the maximum width of a table

我正在尝试设置 table 的最大宽度,但它似乎不起作用。如果 table 中的单词太长,它会自动扩展 table 的宽度。我该如何阻止这种情况发生,而是让太长的词转到下一行?

<style>table {
  max-width: 300px;
}

table,
td {
  border: 1px solid red;
}

div {
  border: 1px solid blue;
  word-wrap: break-word;
}

</style>
<table>

  <tr>
    <td>
      <div> hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello
      </div>
    </td>
  </tr>

</table>

如果你想让你的最大宽度起作用,你需要在 table 上设置 CSS 属性 table-layout: fixed; 并使用 width, 而不是 max-width.

https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout

在 css 部分添加以下规则。

div{
    overflow-wrap: break-word;
    max-width: 300px;

将 max-width 放在 div 中可以解决问题。

<style>
table,td {
border: 1px solid red;
}
div {
border: 1px solid blue;
word-wrap: break-word;
max-width: 300px;
}
</style>
<table>

<tr>
<td>
<div> hellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohellohello </div>
</td>
</tr>

</table>

如果您将宽度分配给容器,

word-wrap: break-word; 将起作用,您正在将此 属性 应用于。因此,您必须将 width:100px; 或所需的宽度分配给 div 标签。

<style type="text/css">
    div {
         width: 100px; /* this will limit the length of the word to 100px */
         border: 1px solid blue;
         word-wrap: break-word;
        }
</style>