Bootstrap 4.5.2表格列宽设置:除指定列外其余列等宽
嘿,我来帮你搞定这个表格列宽的问题!要实现除了update和delete列之外其他列宽度一致的需求,我们可以通过自定义CSS结合Bootstrap的表格类来实现,具体步骤如下:
解决方案思路
- 给表格添加一个自定义类,方便编写针对性样式
- 为需要等宽的列(Date、TimeSlot、Room、Attendees)添加统一类名
- 使用CSS设置表格为固定布局,精准控制等宽列的宽度,同时让操作列(update/delete)根据内容自动适配
修改后的完整代码
HTML部分
<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部分
.custom-table { table-layout: fixed; width: 100%; } .custom-table .equal-width { width: 25%; /* 4个等宽列,每个平分25%的表格宽度 */ } /* 让操作列根据按钮内容自动调整宽度,避免按钮换行 */ .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: auto; white-space: nowrap; }
说明
table-layout: fixed让表格列宽完全由我们设置的样式控制,不会因为内容长度随意变化.equal-width类给4个目标列各分配25%的宽度,确保它们完全等宽- 操作列设置
width: auto和white-space: nowrap,既能适配按钮内容保持合适宽度,又不会因空间不足导致按钮换行
这样设置后,你的表格就能完美实现需求啦!
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

