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

如何在不同浏览器中实现SVG文本垂直居中?

动态SVG文本垂直居中问题(跨浏览器兼容)

我正在开发一款类似Text Mask的动画效果,由于需要动态设置SVG文本,无法直接采用原实现方案。

目前遇到的核心问题是SVG文本无法实现完全垂直居中:使用dominant-baseline:central虽有一定效果,但文本仍未在垂直方向完全居中;尤其当文本字号增大(滚动交互时会触发该变化),偏移问题会更加明显。此外,dominant-baseline:central在Chromium与Firefox浏览器中的表现存在显著差异,Firefox下文本偏上的问题更为突出。

我已尝试调整dominant-baseline的不同取值、修改dy属性、更换SVG定位方式,以下是最接近理想效果的代码示例:

CSS 代码

*,
*:before,
*:after {
  box-sizing: border-box;
  margin: 0;
}

body {
  height: 100vh;
}

img {
  width: 100%;
  height: 100%;
}

.mask {
  position: relative;
  height: 100%;
  width: 100%;
  border: 5px solid hotpink;
}

.mask__svg {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

.mask__svg .mask__text {
  text-anchor: middle;
  text-transform: uppercase;
  font-family: sans-serif;
  font-size: 60rem;
  font-weight: bold;
}

.mask__svg .mask__rect {
  mask: url(#svg-mask);
  fill: white;
}

HTML 代码

<div class="mask">
  <img src="https://images.unsplash.com/photo-1691520673295-9626f624869b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1740&q=80" />
  <svg class="mask__svg">
    <defs>
      <mask id="svg-mask" x="0" y="0" width="100%" height="100%">
        <rect class="mask__rect" x="0" y="0" width="100%" height="100%" fill="white" />
        <text class="mask__text" x="50%" y="50%" text-anchor="middle" dominant-baseline="central">MASK</text>
      </mask>
    </defs>
    <rect class="mask__rect" x="0" y="0" width="100%" height="100%" />
  </svg>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:43:22