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

如何用CSS实现页面居中水印且不改变字体大小?

问题

我希望将#watermark-text放置在页面中心,但目前它始终靠左显示。尝试为#background元素设置top和left属性后,#watermark-text的字体大小变小了。请问如何在不改变字体大小的前提下,让#watermark-text居中显示?

当前使用代码如下:

CSS代码

#background {
  position: absolute;
  background: white;
  z-index: 0;
}

#content {
  z-index: 1;
}

#watermark-text {
  position: absolute;
  color: #eae9e9;
  font-weight: bold;
  font-size: 800px;
}

HTML代码

<div id="background">
  <p id="watermark-text">WaterMark</p>
</div>
<div id="content"></div>
解决方案

字体变小的核心原因是#background默认只包裹内容,没有占满视口空间,设置top/left后容器尺寸被限制,超大字体被迫挤压缩放。解决思路是先让背景容器铺满整个页面,再让内部文字居中:

方法一:定位+transform居中

修改CSS代码如下:

#background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: white;
  z-index: 0;
}

#content {
  position: relative; /* 静态定位元素不支持z-index,需添加相对定位确保层级生效 */
  z-index: 1;
}

#watermark-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 基于自身尺寸偏移,实现精准居中 */
  margin: 0; /* 清除p标签默认外边距,避免居中偏移 */
  color: #eae9e9;
  font-weight: bold;
  font-size: 800px;
}

方法二:Flex布局居中

用Flex布局实现居中更简洁,同样确保背景容器占满视口:

#background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: white;
  z-index: 0;
  display: flex;
  justify-content: center; /* 水平方向居中 */
  align-items: center; /* 垂直方向居中 */
}

#content {
  position: relative;
  z-index: 1;
}

#watermark-text {
  margin: 0;
  color: #eae9e9;
  font-weight: bold;
  font-size: 800px;
}

关键说明

  • width:100vw和height:100vh让背景容器铺满整个浏览器视口,避免因容器尺寸不足导致字体被压缩。
  • 清除p标签默认外边距,防止居中时出现不必要的偏移。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 10:25:17