如何实现表格列在数量较少时仍各占25%宽度?
解决方案
要实现无论表格列数多少,每列都固定占容器宽度的25%(列数不足4时,表格总宽度保持容器100%宽度,列占25%;列数超过4时,支持横向滚动),只需调整表格的宽度属性:
修改后的代码
HTML(无需改动)
<div class="table-container"> <table> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <!-- <th>Column 3</th> <th>Column 4</th> <th>Column 5</th> <th>Column 6</th> <th>Column 7</th> <th>Column 8</th> --> </tr> </thead> <tbody> <tr> <td>Data 1</td> <td>Data 2</td> <!-- <td>Data 3</td> <td>Data 4</td> <td>Data 5</td> <td>Data 6</td> <td>Data 7</td> <td>Data 8</td> --> </tr> <!-- More rows as needed --> </tbody> </table> </div>
CSS(关键修改)
* { box-sizing: border-box; /* Include border and padding in size calculations */ } .table-container { max-width: 80vw; overflow: auto; container-type: inline-size; /* Make it a container that you can query its size */ border: solid; margin: auto; } table { width: max-content; /* 表格宽度由列数总和决定 */ min-width: 100cqw; /* 确保列数不足4时,表格总宽度至少为容器100% */ table-layout: fixed; border-collapse: collapse; } th, td { width: 25cqw; /* Each column occupies 25cqw (25% of the container's width) */ border: 1px solid #ddd; padding: 8px; text-align: left; }
原理说明
width: max-content:让表格宽度自动适配所有列的总宽度(每列固定25cqw),当列数超过4时,表格总宽度会超过容器宽度,触发横向滚动。min-width: 100cqw:强制表格最小宽度为容器的100%(即4列的宽度总和),当列数不足4时,表格不会因为列数少而收缩,每列能保持25cqw的固定宽度,剩余空间留白。- 保留
table-layout: fixed:确保列宽严格遵循设置的25cqw,不受单元格内容长度影响。
内容的提问来源于stack exchange,提问作者Jon You
相关产品推荐
相关产品推荐

