如何使Angular循环生成的特殊表格单元格宽高一致?
问题描述
我创建了一个表格,将<tr>元素的display属性设为table-cell,但不知道如何让它们均等扩展。这么设计是因为表格通过Angular的*ngFor循环生成,每个<tr>标签代表一列。目前各列宽度因内容多少不一致,高度也随内容变化,希望让所有列的宽度和高度保持一致。
当前代码如下:
CSS代码
table { border-collapse: collapse; width: 100%; margin-bottom: 40px; } table .header { display: table-cell; } table .header td { display: block; }
HTML代码
<table> <tr class="header" *ngFor="let header of superficieColumnHeaders"> <td>Column name</td> <td id="header-name">Another Value</td> <td id="body-value">Some specific Value</td> </tr> <tr class="header" *ngFor="let header of superficieColumnHeaders"> <td>Column name</td> <td id="header-name">Another Value</td> <td id="body-value">Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value Some specific Value </td> </tr> </table>
解决方案
通过调整CSS即可实现列宽均分、高度一致的效果,具体修改如下:
table { border-collapse: collapse; width: 100%; margin-bottom: 40px; table-layout: fixed; /* 启用固定表格布局,优先遵循设定宽度 */ } table .header { display: table-cell; width: 1%; /* 所有table-cell按比例均分宽度 */ vertical-align: top; /* 统一内容顶部对齐,可选 */ padding: 0 8px; /* 添加内边距优化排版,可选 */ } table .header td { display: block; word-wrap: break-word; /* 长文本自动换行,避免撑宽单元格 */ }
关键说明:
table-layout: fixed:强制表格按预设宽度布局,忽略内容的自然宽度,确保列宽能均匀分配。.header设置width: 1%:所有作为table-cell的<tr>会自动平分表格的100%宽度,无需手动计算列数,适配动态生成的列。word-wrap: break-word:让内部<td>的长文本自动换行,防止内容溢出导致单元格宽度异常。- 高度自动对齐:
table-cell特性会让同一行内的所有单元格自动匹配最高单元格的高度,无需额外设置。
内容的提问来源于stack exchange,提问作者Gonçalo Bastos
相关产品推荐
相关产品推荐

