首页 > 解决方案 > html table -- 设置列以占用剩余空间,并且至少 300px 宽度

问题描述

如何在 html 表格中间创建一列,并使其填充剩余空间,同时最小宽度为 300px?

这是一个 JSfiddle 显示我正在尝试做的事情。

HTML:

<table>
  <tr>
    <td class="fixed-width">A set width column</td>
    <td class="remaining-width-or-300-pixels">
    A column with long content, to take the remaining space, and at least 300 pixels. It's OK if it has to trucate.
    </td>
    <td class="fixed-width">A set width column</td>
  </tr>
</table>

CSS:

table {
  display: table;
  width: 100%;
  table-layout: fixed;
  white-space: nowrap;
  color: white;
}

table td {
  overflow: hidden;
}

td.fixed-width {
  background: blue;
  width: 200px;
}

td.remaining-width-or-300-pixels {
  background: red;
  overflow: hidden;
  min-width: 300px;
}

如您所见,当您调整面板的宽度时,min-width: 300px;完全被忽略了。

我可以采用任何 css (不是 javascript)解决方法来使其正常工作吗?

编辑:另外,任何使用div元素而不是table,trtd元素的解决方案都不起作用,我正在使用一个需要使用table元素的库。

标签: htmlcsshtml-table

解决方案


我认为问题在于table-layout: fixed;

根据这里,固定的值将设置一个固定的表格布局算法。表格和列的宽度由 table 和 col 的宽度或第一行单元格的宽度设置。可能是最小宽度不适用于 td 的原因。

table {
  display: table;
  width: 100%;
  /* table-layout: fixed; */
  white-space: nowrap;
  color: white;
}

table td {
  overflow: hidden;
}

td.fixed-width {
  background: blue;
  width: 200px;
  min-width: 200px;
}

td.remaining-width-or-300-pixels {
  background: red;
  overflow: hidden;
  min-width: 300px;
 
}
<table>
  <tr>
    <td class="fixed-width">A set width column</td>
    <td class="remaining-width-or-300-pixels">
    A column 
    </td>
    <td class="fixed-width">A set width column</td>
  </tr>
</table>


推荐阅读