如何在HTML表格中拆分过长行并保持列对齐?
需求与问题描述
我需要实现一个HTML表格,满足以下要求:
- 当行的总长度超出可用水平空间时,自动将过长的行拆分为多行,同时保持各列及表头的垂直对齐;若未超出则正常显示。
- 表格的列数是动态的,由用户选择显示哪些列(数据从数据库查询生成)。
此前找到过类似问题但未得到满意解答,其中一个接近需求的方案如下,但该方案虽然能实现行换行,却破坏了列的垂直对齐:
CSS 代码
#table_id { display: block; } #table_id td, #table_id th { display: inline-block; }
HTML 代码
<table id="table_id"> <thead> <tr> <th> Vorname </th> <th> Nachname </th> <th> Klasse </th> <th> Weitere Vornamen </th> <th> m/w </th> <th> Mobil </th> <th> Telefon </th> <th> Adresse </th> <th> PLZ </th> <th> Ort </th> <th> SF </th> <th> EF </th> <th> S3 </th> <th> KU </th> <th> KU+ </th> <th> P5 </th> <th> LS </th> </thead> <tbody> <tr> <td> Dummy </td> <td> Student </td> <td> 23PA </td> <td> One </td> <td> w </td> <td> 0123 456 789 </td> <td> 012 999 99 99 </td> <td> Streetaddress 11 </td> <td> 1111 </td> <td> City </td> <td> PAM </td> <td> PH </td> <td> E </td> <td> BG </td> <td> MU </td> <td> S3 </td> <td> </td> </tr> <tr> <td> Another </td> <td> Student </td> <td> 23PA </td> <td> </td> <td> m </td> <td> 0123 456 789 </td> <td> 012 999 99 99 </td> <td> Hauptstrasse 100 </td> <td> 2222 </td> <td> Other City </td> <td> PAM </td> <td> WR </td> <td> E </td> <td> BG </td> <td> </td> <td> EF </td> <td> </td> </tr> </tbody> </table>
我曾考虑用CSS Grid实现,但由于需要通过Weasyprint库导出PDF,而该库暂不支持CSS Grid,因此无法采用。
内容的提问来源于stack exchange,提问作者Tobias Bäumlinn
相关产品推荐
相关产品推荐

