如何实现Bootstrap表格与嵌套表格的列宽调整及表头元素对齐
解决方案
要实现父表头和嵌套表格列对齐,按以下步骤修改即可:
- 给父表格追加
table-layout: fixed样式,强制列宽按配置的比例固定渲染,不会随内容自适应偏移 - 给父表格包裹内容的
<td>加p-0类,消除默认内边距避免嵌套表格偏移 - 嵌套表格添加
table table-sm w-100 m-0类,让其占满父容器宽度,同时和父表的尺寸规格保持一致,消除默认边距 - 给父表头的
<th>和嵌套表格第一行对应的<td>设置统一的宽度规则 - 修正嵌套表格第二行备注字段的
colspan属性为9,和总列数匹配,避免列宽计算异常
自定义CSS(按需添加)
/* 自定义宽度类,可根据需求调整比例 */ .w-10 { width: 10%; } .w-20 { width: 20%; }
修改后完整代码
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <table class="table table-striped table-sm" style="table-layout: fixed;"> <thead> <tr> <th class="w-20">Project</th> <th class="w-10">Date</th> <th class="w-10">Starting</th> <th class="w-10">Ending</th> <th class="w-10">+/-</th> <th class="w-10">Duration</th> <th class="w-10">Rate</th> <th class="w-10">Total</th> <th class="w-10">Action</th> </tr> </thead> <tbody> <tr> <td colspan="9" class="p-0"> <form method="post" action="/edit"> <table class="table table-sm w-100 m-0"> <tbody> <tr> <td class="w-20"><input type="text" class="form-control form-control-sm" placeholder="Project"></td> <td class="w-10"><input type="date" class="form-control form-control-sm"></td> <td class="w-10"><input type="time" class="form-control form-control-sm"></td> <td class="w-10"><input type="time" class="form-control form-control-sm"></td> <td class="w-10"><input type="number" step="0.25" class="form-control form-control-sm"></td> <td class="w-10"><input type="number" class="form-control form-control-sm" disabled=""></td> <td class="w-10"> <div class="input-group"> <span class="input-group-text"><i class="fas fa-dollar-sign"></i></span> <input type="number" class="form-control form-control-sm"> </div> </td> <td class="w-10"> <div class="input-group"> <span class="input-group-text"><i class="fas fa-dollar-sign"></i></span> <input disabled="" type="number" class="form-control form-control-sm"> </div> </td> <td class="w-10"> <button type="submit" class="btn btn-outline-primary btn-sm">Save</button> <a href="/delete" role="button" class="btn btn-outline-danger btn-sm">Delete</a> </td> </tr> <tr> <td colspan="9"> <input type="text" class="form-control form-control-sm" placeholder="Notes"> </td> </tr> </tbody> </table> </form> </td> </tr> </tbody> </table>
说明
之前直接加col-sm-*不生效的原因是栅格类默认适配flex布局,普通table布局下需要开启table-layout: fixed才能按配置的宽度渲染。如果不需要自定义宽度类,也可以直接给对应列加内联style="width: xx%"实现更灵活的控制。
内容的提问来源于stack exchange,提问作者craig
相关产品推荐
相关产品推荐

