如何用Bootstrap 5实现行间距+行边框无列边框的表格布局?
解决Bootstrap 5表格行带边框、列无边框且行间距的问题
你的代码里有几个关键问题导致样式不符合需求,调整后就能实现目标效果:
- 移除冲突的Bootstrap类:
table-bordered会给所有单元格添加边框,这是列间出现边框的核心原因,必须去掉。 - 修正CSS选择器:你写的
.giro-table .giro-table tr是无效选择器,应该简化为.giro-table tr。 - 清除单元格默认边框:Bootstrap的表格单元格默认自带边框,需要手动清除
td和th的边框。 - 调整行边框与间距:通过
border-collapse: separate和border-spacing实现行间距,给每行添加完整边框。
修正后的完整代码:
<style> .giro-table { border-collapse: separate; border-spacing: 0 15px; /* 上下行间距15px,左右保持对齐无间距 */ width: 100%; } /* 给表头、表体的行统一添加边框 */ .giro-table thead tr, .giro-table tbody tr { border: 1px solid #A8A8AD; border-radius: 4px; /* 可选:给行添加圆角优化视觉 */ } .giro-table th { background: #A8A8AD; border: none; /* 清除表头单元格的默认边框 */ padding: 20px; } .giro-table td { border: none; /* 清除表体单元格的默认边框 */ padding: 20px; } /* 可选:如果不需要斑马纹,覆盖table-striped的默认背景色 */ .giro-table tbody tr:nth-of-type(odd) { background-color: transparent; } </style> <table class="table table-hover giro-table" style="max-width:700px;margin:0 auto;"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <td>Mark</td> <td>Otto</td> <td>@mdo</td> <td>@twitter</td> </tr> <tr> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> <td>@twitter</td> </tr> <tr> <td colspan="2">Larry the Bird</td> <td>@twitter</td> <td>@twitter</td> </tr> </tbody> </table>
关键说明:
- 去掉
table-bordered后,直接给tr设置边框,实现每行独立带框的效果。 border-spacing: 0 15px精准控制行与行的垂直间距,左右保持对齐。- 给
th和td设置border: none,彻底消除列之间的边框。 - 如果不需要斑马纹效果,可以直接移除
table-striped类,或者用CSS覆盖默认背景色。
内容的提问来源于stack exchange,提问作者gil.code
相关产品推荐
相关产品推荐

