HTML表最后td采取剩余宽度

时间:2016-07-02 16:57:07

标签: html css html-table

我有一张TR和2个TD的表。我希望第一个TD根据其内容自动调整宽度,第二个TD使用宽度的其余部分。

这就是我所拥有的:

<table style="width: 100%;">
  <tr>
    <td>short content</td>
    <td>long content</td>
  </tr>
</table>

整个表格宽度为100%(我想要它),但我不知道如何调整TD宽度以达到我的目标。

2 个答案:

答案 0 :(得分:4)

你可以给第一个td一个小宽度,例如1pxwhite-space: nowrap;

table {
  width: 100%;
  border-collapse: collapse;
}
td {
  border: 1px solid red;
}
td:first-child {
  width: 1px;
  white-space: nowrap;
}
<table>
  <tr>
    <td>short content</td>
    <td>long content</td>
  </tr>
</table>

或者,给最后一个td一个大的宽度,例如100%

table {
  width: 100%;
  border-collapse: collapse;
}
td {
  border: 1px solid red;
}
td:first-child {
  white-space: nowrap;
}
td:last-child {
  width: 100%;
}
<table>
  <tr>
    <td>short content</td>
    <td>long content</td>
  </tr>
</table>

答案 1 :(得分:0)

在除最后一个单元格之外的所有单元格上设置white-space: nowrap,并为最后一个单元格设置100%的宽度,对我来说很有效:

    td:not(:last-child), th:not(:last-child) {
      white-space: nowrap;
    }

    td:last-child, th:last-child {
      width: 100%;
    }

这将确保在有可用空间的情况下,文本换行仍然有效,同时仍在填充表格。