You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用HTML和CSS实现表格TD等高(适配WeasyPrint+Django)

解决WeasyPrint中表格行等高问题

需求:在Django中使用WeasyPrint制作模板时,实现表格同一行内所有<td>的高度与该行最高<td>的高度一致,仅通过HTML和CSS实现。此前尝试的CSS代码未解决问题:

.equal-row-height-table {
  border-collapse: collapse;
  width: 100%;
}

.equal-row-height-table td,
.equal-row-height-table th {
  border: 1px solid black;
  padding: 5px;
  vertical-align: top;
}

.equal-row-height-table tr {
  page-break-inside: avoid;
}

.equal-row-height-table td:first-child {
  width: 30px;
}

.equal-row-height-table td:nth-child(2) {
  width: 50%;
}

.equal-row-height-table td:nth-child(n+3) {
  width: 10%;
  text-align: right;
}

.equal-row-height-table .product-info {
  display: flex;
  flex-direction: column;
}

.equal-row-height-table .product-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.equal-row-height-table .product-details {
  display: flex;
  justify-content: space-between;
  font-size: 0.9em;
} 

解决方案

调整CSS,确保单元格和内部容器能继承并填满行高,具体修改如下:

.equal-row-height-table {
  border-collapse: collapse;
  width: 100%;
  table-layout: fixed; /* 可选,稳定列宽布局 */
}

.equal-row-height-table td,
.equal-row-height-table th {
  border: 1px solid black;
  padding: 5px;
  vertical-align: top;
  height: 100%; /* 关键:让单元格继承行的高度 */
}

.equal-row-height-table tr {
  page-break-inside: avoid;
}

.equal-row-height-table td:first-child {
  width: 30px;
}

.equal-row-height-table td:nth-child(2) {
  width: 50%;
}

.equal-row-height-table td:nth-child(n+3) {
  width: 10%;
  text-align: right;
}

.equal-row-height-table .product-info {
  height: 100%; /* 让内部容器填满单元格高度 */
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 可选,优化内容垂直分布 */
}

.equal-row-height-table .product-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.equal-row-height-table .product-details {
  display: flex;
  justify-content: space-between;
  font-size: 0.9em;
}

原理说明

之前的代码中,单元格内的flex容器未填满单元格高度,导致表格行无法根据最高单元格的内容自动统一高度。通过给<td>设置height: 100%,让单元格继承行的高度;同时给内部的.product-info容器设置height: 100%,确保容器填满单元格,最终实现同一行所有单元格高度一致。

内容的提问来源于stack exchange,提问作者Shital Nerikar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:36:02