Bootstrap 4.5.2表格列宽设置:除更新/删除列外其余列等宽
解决Bootstrap 4.5.2表格列宽自定义问题
嘿,我来帮你搞定这个表格列宽的需求!你想要除了update和delete列保持原有宽度外,其他列宽度一致,其实通过简单的自定义CSS就能实现,我一步步给你说:
首先先清理下你现有代码里的小冗余:你的<tr>和<td>标签上都加了table类,这其实没必要——Bootstrap的table类只需要加在最外层的<table>标签上就够了,多余的类可能会导致样式冲突,先把它们去掉。
接下来给你两种靠谱的解决方案:
方案一:固定表格布局+百分比分配宽度
这种方法最可控,适合需要精确分配列宽的场景:
第一步:修改HTML结构
给表格加一个自定义类custom-table,同时给需要等宽的列(Date、TimeSlot、Room、Attendees)的<th>和<td>都加上equal-width类:
<table class="table table-bordered table-responsive-sm table-hover custom-table"> <thead> <tr> <th class="equal-width">Date</th> <th class="equal-width">TimeSlot</th> <th class="equal-width">Room</th> <th class="equal-width">Attendees</th> <th>update</th> <th>delete</th> </tr> </thead> <tbody> <tr> <td class="equal-width">Date</td> <td class="equal-width">Time</td> <td class="equal-width">Room</td> <td class="equal-width">invitee</td> <td style="display: none">reservationid</td> <td style="display: none">invitedby</td> <td style="display: none">workspace</td> <td> <a onclick="onUpdate()" style="color: #007bff; cursor: pointer"> <i class="fa fa-pencil-square-o" aria-hidden="true"></i> </a> </td> <td> <a onclick="onDelete()" style="color: #007bff; cursor: pointer"> <i class="fa fa-trash" aria-hidden="true"></i> </a> </td> </tr> </tbody> </table>
第二步:添加自定义CSS
利用table-layout: fixed让表格布局固定,然后给等宽列分配宽度,update和delete列自动适配内容:
/* 固定表格布局,避免内容打乱列宽 */ .custom-table { table-layout: fixed; width: 100%; } /* 给4个等宽列各分配20%的宽度,剩下20%留给update和delete列自适应 */ .custom-table .equal-width { width: 20%; }
方案二:固定操作列宽度+动态分配剩余宽度
如果你想让update和delete列保持固定宽度(比如刚好放下图标),可以用这种方式:
.custom-table { table-layout: fixed; width: 100%; } /* 给update和delete列设置固定宽度,比如50px */ .custom-table th:last-child, .custom-table td:last-child, .custom-table th:nth-last-child(2), .custom-table td:nth-last-child(2) { width: 50px; } /* 剩余宽度平均分给4个列 */ .custom-table .equal-width { width: calc((100% - 100px) / 4); }
你可以根据图标的实际大小调整50px这个值,确保操作列刚好放下图标,不会浪费空间也不会挤压内容。
另外,你代码里的隐藏列(reservationid、invitedby这些)用display: none是没问题的,它们不会占用表格的宽度空间,完全不影响我们的列宽设置。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

