基于table-layout实现行标题(模拟colspan效果)
解决方案
核心思路
将每一行的单元格与标题封装为独立的表格容器,利用table-caption特性实现标题在下方且不干扰单元格布局,同时保证容器高度自适应标题长度。
实现代码
CSS 代码
.table { display: table; width: 100%; float: left; border-collapse: collapse; } .row-group { display: table; width: 100%; margin-bottom: 8px; /* 可选,行与行之间的间距 */ } .row { display: table-row; } .cell { display: table-cell; border: 1px solid black; vertical-align: middle; /* 实现单元格垂直对齐 */ } .caption { display: table-caption; caption-side: bottom; text-align: left; /* 可选,标题左对齐 */ padding-top: 4px; /* 可选,标题与单元格的间距 */ }
HTML 代码
<div class="table"> <div class="row-group"> <div class="row"> <div class="cell">First</div> <div class="cell">Hello stackoverflow</div> </div> <div class="caption">I am the row caption</div> </div> <div class="row-group"> <div class="row"> <div class="cell">I am second</div> <div class="cell">Hello world!</div> </div> <div class="caption">I am the row caption</div> </div> <div class="row-group"> <div class="row"> <div class="cell">3</div> <div class="cell">Hello</div> </div> <div class="caption">I am the row caption</div> </div> </div>
方案说明
- 每个
row-group作为独立表格容器,确保单元格宽度仅由自身内容决定,标题不参与宽度计算 caption通过caption-side: bottom固定在单元格下方,且容器高度会自动适配标题长度,无需绝对定位vertical-align: middle实现单元格内容垂直对齐- 全程使用div模拟表格结构,未使用table标签,满足遗留代码限制
内容的提问来源于stack exchange,提问作者alexandar_123
相关产品推荐
相关产品推荐

