能否通过CSS将表格最后一行的单元格设置为垂直排列?
实现表格最后一行单元格垂直排列
你有如下基础表格代码:
<table border="1"> <tr> <td>Row 1, Cell 1</td> <td>Row 1, Cell 2</td> </tr> <tr> <td>Row 2, Cell 1</td> <td>Row 2, Cell 2</td> </tr> <tr> <td>Row 3, Cell 1</td> <td>Row 3, Cell 2</td> </tr> </table>
要让最后一行的单元格垂直排列,可以通过CSS修改最后一行的布局方式,具体实现如下:
解决方案代码
<table border="1"> <tr> <td>Row 1, Cell 1</td> <td>Row 1, Cell 2</td> </tr> <tr> <td>Row 2, Cell 1</td> <td>Row 2, Cell 2</td> </tr> <tr> <td>Row 3, Cell 1</td> <td>Row 3, Cell 2</td> </tr> </table> <style> /* 选中表格的最后一行 */ table tr:last-child { /* 将行设置为flex布局,垂直排列子元素 */ display: flex; flex-direction: column; /* 确保行占满表格宽度 */ width: 100%; } /* 让最后一行的每个单元格占满行宽 */ table tr:last-child td { width: 100%; /* 保持边框盒模型,避免边框超出宽度 */ box-sizing: border-box; } </style>
原理说明
- 通过
tr:last-child选择器精准定位表格的最后一行 - 将该行的布局从默认的表格布局改为flex布局,设置
flex-direction: column让单元格垂直堆叠 - 设置
width: 100%确保行和单元格都占满表格宽度,保持整体布局一致性
你也可以用Grid布局实现同样效果,只需把CSS部分替换为:
table tr:last-child { display: grid; grid-template-columns: 1fr; width: 100%; } table tr:last-child td { width: 100%; box-sizing: border-box; }
内容的提问来源于stack exchange,提问作者in43sh
相关产品推荐
相关产品推荐

