HTML 表格,某些列自动调整,其他列固定宽度

标签 html css html-table

我正在尝试创建一个符合以下要求的表:

  1. 表格宽度必须定义为 0 - 浏览器应根据列宽计算宽度(这是为了适应列调整大小插件)。
  2. 某些列可能会收到固定宽度(例如 50 像素);
  3. 没有固定宽度的列必须自动适应内容。

我创建了一个 small example为了说明问题 - 正如您所见,第 3 列的宽度保持为 0,因此不可见。

编辑:如果删除了“table-layout: fixed”。第三列出现,但固定宽度被忽略,所有列变为自动调整。

HTML

<table>
<tr>
    <td class="cell header" id="header1">Header 1</td>
    <td class="cell header" id="header2">Header 2</td>
    <td class="cell header" id="header3">Header 3</td>
</tr>
<tr>
    <td class="cell">Cell 1</td>
    <td class="cell">Cell 2</td>
    <td class="cell">Very looooong content</td>
</tr>
</table>

CSS

table {
    table-layout: fixed;
    width: 100%;
    border: 1px solid #696969;
}

.cell {
    color: #898989;
    border: 1px solid #888;
    padding: 2px;
    overflow: hidden;
}

.header {
    background-color: lightsteelblue;
    color: black;
}

#header1, #header2 {
    width: 50px;
}

这可能吗?任何帮助将不胜感激...

最佳答案

table-layout: fixed 和宽度为 0 在你的 table 上是不可能的。

形成W3 Spec section 17.5.2.1 :

In the fixed table layout algorithm, the width of each column is determined as follows:

  1. A column element with a value other than 'auto' for the 'width' property sets the width for that column.
  2. Otherwise, a cell in the first row with a value other than 'auto' for the 'width' property determines the width for that column. If the cell spans more than one column, the width is divided over the columns.
  3. Any remaining columns equally divide the remaining horizontal table space (minus borders or cell spacing).

但是,当您执行自动布局(在第 17.5.2.2 节中描述)时,您的宽度将被调整以适应您的内容,并且仅在可能的情况下使用提供的宽度。例如,如果每列的最小宽度之和超过了表格的容器宽度,则所有内容都会移动以适合您设置的宽度。

还需要注意的是:

UAs are not required to implement this algorithm to determine the table layout in the case that 'table-layout' is 'auto'; they can use any other algorithm even if it results in different behavior.

所以看起来答案很不幸是一个冗长的“不”:(

关于HTML 表格,某些列自动调整,其他列固定宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13671488/

相关文章:

html - 根据最宽的元素使所有元素的宽度相等

javascript - 使用 jQuery 从 html 表中动态选择列

css - canvas vs. webGL vs. CSS 3d -> 选择哪个?

javascript - 自动计算多个下拉选择

html - 如何创建一个与另一个相似的 UL 菜单

css - Bootstrap 3 特定行的替代悬停颜色

html - Angular 2背景图像不渲染

ios - 加入UICollectionViewCell像HTML的rowpan表一样吗?

html - 如何在td的右上角添加div?

html - CSS匹配行中其他元素的高度