table-layout: fixed失效问题

施英哲
2023-12-01

固定表格布局: fixed

固定表格布局与自动表格布局相比,允许浏览器更快地对表格进行布局。
在固定表格布局中,水平布局仅取决于表格宽度、列宽度、表格边框宽度、单元格间距,而与单元格的内容无关。
通过使用固定表格布局,用户代理在接收到第一行后就可以显示表格。

对表格设置table-layout:fixed属性以后,如果表格的第一行tr中的td设置过单元格合并,后面tr中的td无论如何设置宽度都没有任何效果

这里因为第一行是标题,使用了colspan合并了单元格,导致了table-layout: fixed失效,列宽度不一致

<div style="max-height: 70vh;width: ${reportList?size*100+400}px;overflow-y: auto;"
     class="fixed-table-container">
    <table class="table table-hover table-striped"
           style="table-layout: fixed;width: ${reportList?size*100+400}px;">
        <tr class="bold_img" style="background:rgb(55, 140, 214);color:white;font-weight:bold;">
            <th class="text-center" colspan="${reportList?size+ 2}">小游戏完成圈数情况</th>
        </tr>
        ...表格循环生成
    </table>
</div>

通过col标签为后续每列设定固定的宽度

在html中,col标签是使用来为表格中一个或多个列定义属性值,通过该标签可以同时给整个列应用样式,不需要重复为每个单元格或每一行设置样式

<div style="max-height: 70vh;width: ${reportList?size*100+400}px;overflow-y: auto;"
     class="fixed-table-container">
    <table class="table table-hover table-striped"
           style="table-layout: fixed;width: ${reportList?size*100+400}px;">
        此处设定后续每列固定宽度
        <tr>
            <col width="200"/>
            <#list reportList as rl >
                <col width="100"></col>
            </#list>
            <col width="180"/>
        </tr>
        <tr class="bold_img" style="background:rgb(55, 140, 214);color:white;font-weight:bold;">
            <th class="text-center" colspan="${reportList?size+ 2}">小游戏完成圈数情况</th>
        </tr>
        ...表格循环生成
    </table>
</div>
 类似资料: