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

mPDF中固定宽高div内部内容如何实现垂直居中

mPDF 对现代 CSS 特性支持度有限,你之前尝试的 display: table/table-cell、绝对定位居中等方案都不被兼容,所以无法生效。可以根据内容场景选择以下兼容方案:


单行内容场景

直接将容器的 line-height 设置为和高度相等即可,是兼容性最高的方案:

<div style="width:280px; float:left; padding:0 10px; height: 310px; line-height: 310px; text-align:center;">
  <p style="margin:0">Hello World</p>
</div>

如果内部元素自带默认边距,需要手动清零避免偏移。


多行内容场景

使用原生 table 标签实现,不要用 CSS 模拟 table 布局,mPDF 对原生 table 的垂直对齐属性支持完好:

<div style="width:280px; float:left; padding:0 10px; height: 310px;">
  <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td align="center" valign="middle">
        <p>Hello World</p>
        <p>多行内容测试</p>
      </td>
    </tr>
  </table>
</div>

你之前使用 table 替代 div 无效的大概率原因是遗漏了给 table 设置 height:100% 继承外层容器高度,或者给 table 加了多余的样式干扰。


内容的提问来源于stack exchange,提问作者Trevor Jordan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:45:07