如何不使用flexbox,用表格实现justify-content: space-between效果
用表格实现类似
justify-content: space-between的对齐效果 要实现第一个元素左对齐、最后一个元素右对齐且所有内容间距均等的效果,直接给单元格设置均等列宽会因为内容长度差异导致视觉间距不均,你可以通过以下两种方式解决:
方案一:添加空单元格填充间隔(推荐)
这种方式能完全匹配space-between的边缘对齐+均等间距效果,原理是用空单元格平分表格剩余空间:
<table style="width: 100%;"> <tr> <!-- 第一个内容:左对齐 --> <td style="text-align: left; white-space: nowrap;">Apples</td> <!-- 空单元格,自动平分剩余空间 --> <td style="width: 100%;"></td> <!-- 中间内容:居中对齐 --> <td style="text-align: center; white-space: nowrap;">Blueberries</td> <!-- 空单元格,自动平分剩余空间 --> <td style="width: 100%;"></td> <!-- 中间内容:居中对齐 --> <td style="text-align: center; white-space: nowrap;">Bananas</td> <!-- 空单元格,自动平分剩余空间 --> <td style="width: 100%;"></td> <!-- 最后一个内容:右对齐 --> <td style="text-align: right; white-space: nowrap;">Strawberries</td> </tr> </table>
关键细节
- 表格设置
width: 100%,占满父容器宽度 - 内容单元格添加
white-space: nowrap,避免内容换行打乱布局 - 空单元格数量为「内容数量-1」,且都设
width: 100%,表格会自动将剩余空间平均分配给这些空单元格,确保内容间距完全均等
方案二:固定表格布局(无需空单元格)
如果不想额外添加空单元格,可通过固定布局分配宽度,适合对边缘间距要求不严格的场景:
<table style="width: 100%; table-layout: fixed;"> <tr> <td style="text-align: left; width: auto; white-space: nowrap;">Apples</td> <td style="text-align: center; width: 33.33%; white-space: nowrap;">Blueberries</td> <td style="text-align: center; width: 33.33%; white-space: nowrap;">Bananas</td> <td style="text-align: right; width: auto; white-space: nowrap;">Strawberries</td> </tr> </table>
关键细节
table-layout: fixed强制表格按指定宽度规则布局- 首尾单元格设
width: auto,由内容自身宽度撑开 - 中间单元格平分剩余宽度,保证内容之间的间距均等
内容的提问来源于stack exchange,提问作者Lee Vannes
相关产品推荐
相关产品推荐

