css - 对表格使用 calc()

标签 css html-table fixed-width css-calc

我正在尝试获取具有固定宽度 td 和可变宽度 td 的表格。

我正在使用 CSS calc() 函数,但不知何故我似乎无法在表格中使用 %

这就是我目前所拥有的:

<table border="0" style="width:100%;border-collapse:collapse;">
    <tr style="width:100%">
        <td style="width:30px;">1</td> <!--Fixed width-->
        <td style="width: calc( (100% - 230px) / 100 * 40);">Title</td> <!--Width should be 40% of the remaining space-->
        <td style="width: calc( (100% - 230px) / 100 * 40);">Interpret</td> <!--Width should be 40% of the remaining space-->
        <td style="width: calc( (100% - 230px) / 100 * 20);">Album</td> <!--Width should be 20% of the remaining space-->
        <td style="width:80px;">Year</td><!--Fixed width-->
        <td style="width:180px;">YouTube</td><!--Fixed width-->
    </tr>
</table>

在我看来,它应该可以工作,但事实并非如此。

有人知道怎么解决吗?或者对我如何实现目标有其他建议?

最佳答案

表格在分配列空间方面有困难的规则,因为默认情况下它们根据单元格的内容分配空间。 Calc (atm) 无法使用它。

但是你可以做的是设置 table-layout table 的属性强制子 td 元素获得您声明的确切宽度。为此,您还需要在 table 上设置一个宽度(100% 有效)。

table{
   table-layout:fixed; /* this keeps your columns with at the defined width */
   width: 100%;        /* a width must be specified */

   display: table;     /* required for table-layout to be used 
                          (since this is the default value it is normally not necessary;
                          just included for completeness) */
}

然后在其余列上使用纯百分比。

td.title, td.interpret{
    width:40%;
}
td.album{
    width:20%;
}

用完固定宽度列的空间后,剩余空间分配给相对宽度的列。

为此,您需要默认显示类型 display: table(相对于 display: block)。然而,这意味着您不能再为表格设置高度(包括min-heightmax-height)。

See your modified Example.

关于css - 对表格使用 calc(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19259569/

相关文章:

html - 列宽超过容器宽度的表格

html - 带有 table-layout=auto 的 HTML 表格中的固定宽度列

perl - 如何在 perl 中解析多行、固定宽度的文件?

javascript - 使用 CSS 和 wicket 操作 HTML 表格中 div 类的高度

javascript - 删除列后使 IE8 重新呈现表格

select - 尊重空白填充以固定宽度显示列 <select>

css - 嵌套导航链接在 IE 9 中消失得太快

javascript - 在文本 Angular 文本上添加工具提示

html - 更改最后一个字母颜色

css - 原生 SVG 循环动画