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

如何根据文本的最高点和最低点实现垂直对齐?

文本垂直居中实现方案

需求说明

我希望实现文本垂直居中,使文本的最高点与最低点到其所在div的上下边缘距离相等。

现有CSS代码

padding-left: 30px;
font-family: 'Playfair Display', serif;
font-weight: 100;
width: 140%;
line-height: 68px;
color: #fff;
font-size: 46px;
border-style: solid;
border-color: #1faf2d;
background-color: #1faf2d;
margin-bottom: 0 !important;
margin-top: 38px;

当前效果

当前文本显示效果

解决方案

要实现文本严格垂直居中(文本最高点/最低点到容器上下边缘距离相等),可以通过以下几种方法调整:

  • 方法一:Flex布局实现居中
    给文本所在容器添加Flex属性,通过align-items: center实现垂直居中,同时可移除原有的line-height设置避免干扰:

    display: flex;
    align-items: center;
    padding-left: 30px;
    font-family: 'Playfair Display', serif;
    font-weight: 100;
    width: 140%;
    color: #fff;
    font-size: 46px;
    border-style: solid;
    border-color: #1faf2d;
    background-color: #1faf2d;
    margin-bottom: 0 !important;
    margin-top: 38px;
    /* 若需要固定容器高度,添加height属性 */
    height: 68px;
    
  • 方法二:精准控制内边距与行高
    由于Playfair Display这类衬线字体的字形上下留白不一致,单纯设置line-height无法实现严格居中。可调整上下内边距,配合line-height: 1实现:

    padding-left: 30px;
    padding-top: 8px; /* 根据字体实际字形微调数值 */
    padding-bottom: 8px;
    font-family: 'Playfair Display', serif;
    font-weight: 100;
    width: 140%;
    line-height: 1;
    color: #fff;
    font-size: 46px;
    border-style: solid;
    border-color: #1faf2d;
    background-color: #1faf2d;
    margin-bottom: 0 !important;
    margin-top: 38px;
    /* 固定容器高度时,设为字体高度+上下内边距总和 */
    height: 68px;
    
  • 方法三:CSS Grid布局快速居中
    利用Grid的place-items: center属性,一键实现水平+垂直居中:

    display: grid;
    place-items: center;
    padding-left: 30px;
    font-family: 'Playfair Display', serif;
    font-weight: 100;
    width: 140%;
    color: #fff;
    font-size: 46px;
    border-style: solid;
    border-color: #1faf2d;
    background-color: #1faf2d;
    margin-bottom: 0 !important;
    margin-top: 38px;
    height: 68px;
    

注意事项

  • 若容器未设置固定高度,Flex/Grid布局会自动适配文本高度并完成居中;
  • 衬线字体的字形差异可能需要微调内边距,建议在字体加载完成后再调整样式;
  • 可移除border-style: solid或调整border-width,避免边框占用空间影响上下距离计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 03:03:32