如何在单个HTML <tr>元素中语义化实现两行视觉展示效果
实现方案
完全不需要使用grid等布局,仅用原生相关标签即可实现,以下是两种符合语义的可选方案: 方案1:
HTML允许单个表格内存在多个
CSS代码
/* 按tbody分组设置背景色,保证关联行背景统一 */ tbody:nth-of-type(even) { background: #ccc; } /* 关联行取消多余边距,保证视觉连贯 */ .related-row td { border: 0; padding-top: 0; }
HTML代码
<table border="1" style="width: 100%;border-collapse: collapse;"> <thead> <tr> <th>id</th> <th>col 1</th> <th>col 2</th> </tr> </thead> <!-- 第一个关联条目组 --> <tbody> <tr> <td>1</td> <td>text</td> <td>text</td> </tr> <tr class="related-row"> <td colspan="3">row that relates to id 1</td> </tr> </tbody> <!-- 第二个关联条目组 --> <tbody> <tr> <td>2</td> <td>text</td> <td>text</td> </tr> <tr class="related-row"> <td colspan="3">row that relates to id 2</td> </tr> </tbody> </table>
方案2:单个
如果必须把所有关联内容放在同一个
CSS代码
table { position: relative; width: 100%; border-collapse: collapse; } tr:nth-child(even) { background: #ccc; } td { vertical-align: top; padding: 4px; border: 1px solid #000; } /* 固定第一行高度,给关联内容留出位置 */ .first-line { height: 22px; } /* 关联内容跨全列显示 */ .related-content { position: absolute; left: 0; right: 0; padding: 4px; height: 22px; line-height: 22px; }
HTML代码
<table> <thead> <tr> <th>id</th> <th>col 1</th> <th>col 2</th> </tr> </thead> <tbody> <tr style="padding-bottom: 26px;"> <td><span class="first-line">1</span><span class="related-content">row that relates to id 1</span></td> <td><span class="first-line">text</span></td> <td><span class="first-line">text</span></td> </tr> <tr style="padding-bottom: 26px;"> <td><span class="first-line">2</span><span class="related-content">row that relates to id 2</span></td> <td><span class="first-line">text</span></td> <td><span class="first-line">text</span></td> </tr> </tbody> </table>
内容的提问来源于stack exchange,提问作者Alvie Mahmud
相关产品推荐
相关产品推荐

