如何为HTML表格设置固定列宽?解决列宽随内容撑开问题
问题:表格列宽被内容撑开,设置固定宽度无效
我设置了表格列的固定宽度(50px/300px),但当单元格内容过长时,列还是会被撑开以容纳内容,请问如何避免这种情况?
我的代码
CSS
.gastos { width: 50px; white-space: nowrap; } .titulos_egresos { width: 300px; white-space: nowrap; }
HTML
<table class="table table-bordered border-dark table-sm"> <thead> <tr class="table-active"> <th scope="col"> <h5 class="text-center titulos_egresos">1. Detalle de sueldos y cargas sociales</h5> </th> <th scope="col"> <h5 class="text-center gastos">Gastos A</h5> </th> <th scope="col"> <h5 class="text-center gastos">Gastos B</h5> </th> <th scope="col"> <h5 class="text-center gastos">Gastos C</h5> </th> <th scope="col"> <h5 class="text-center gastos">Gastos D</h5> </th> <th scope="col"> <h5 class="text-center gastos">Total</h5> </th> </tr> </thead> <tbody> <!--For each gastos A--> {{#each gastos_a}} <tr class=""> <td> {{titulo}}</td> <td class="">${{monto_parcial}}</td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table>
解决方法
问题根源有两个:
- 表格默认
table-layout: auto,会优先根据内容自动调整列宽,忽略固定宽度设置 - 宽度样式被加在了
<h5>标签上,而决定列宽的是表格的<th>/<td>单元格本身
修改后的代码
CSS
/* 给表格设置固定布局,强制使用预设列宽 */ .table-fixed { table-layout: fixed; width: 100%; /* 必须设置宽度,fixed布局才能生效 */ } /* 直接给单元格设置固定宽度 */ .titulos_egresos-col { width: 300px; } .gastos-col { width: 50px; } /* 处理内容溢出,避免撑破单元格 */ .table-fixed th, .table-fixed td { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; /* 内容过长时显示省略号,可选 */ }
HTML
<table class="table table-bordered border-dark table-sm table-fixed"> <thead> <tr class="table-active"> <th scope="col" class="titulos_egresos-col"> <h5 class="text-center">1. Detalle de sueldos y cargas sociales</h5> </th> <th scope="col" class="gastos-col"> <h5 class="text-center">Gastos A</h5> </th> <th scope="col" class="gastos-col"> <h5 class="text-center">Gastos B</h5> </th> <th scope="col" class="gastos-col"> <h5 class="text-center">Gastos C</h5> </th> <th scope="col" class="gastos-col"> <h5 class="text-center">Gastos D</h5> </th> <th scope="col" class="gastos-col"> <h5 class="text-center">Total</h5> </th> </tr> </thead> <tbody> {{#each gastos_a}} <tr> <td>{{titulo}}</td> <td>${{monto_parcial}}</td> <td></td> <td></td> <td></td> <td></td> </tr> {{/each}} </tbody> </table>
关键说明
table-layout: fixed会让表格严格按照设置的列宽分配空间,不再随内容变化- 必须给表格设置
width(比如100%),固定布局才能生效 text-overflow: ellipsis是可选设置,若不需要省略号,仅保留overflow: hidden即可让过长内容截断隐藏
内容的提问来源于stack exchange,提问作者user19729277
相关产品推荐
相关产品推荐

