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

React/CSS求助:如何将文字定位在图片上方并在父div内居中

问题根因

你给文字设置position: absolute后,没有给它的直接父容器设置定位基准,绝对定位元素默认会以整个页面视口为参照定位,所以才会出现文字相对于页面居中的问题,和你设置的top:50%、left:50%属性本身无关。

解决方法

只需要两步修改即可实现父容器内居中效果:

  1. 给包裹图片和文字的父div添加position: relative属性,让内部绝对定位的元素以这个父容器为定位基准
  2. 修正flex布局的属性拼写,可额外加gap调整两个名字的间距、给h1清除默认外边距避免布局偏移
    修改后的完整代码如下:
<div style={{ display: `flex`, flexDirection: `column` }}>
    {/* image and title */}
    {/* 给父容器加position: relative作为定位基准 */}
    <div style={{position: 'relative'}}>
      <StaticImage
        src="../images/home.png"
        width={1000}
        quality={100}
        formats={["auto", "webp", "avif"]}
        alt="home image"
        style={{ marginBottom: `1rem` }}
      />
      <div style={{
            position: `absolute`,
            top: `50%`,
            left: `50%`,
            transform: `translate(-50%, -50%)`,
            zIndex: 2,
            display: `flex`,
            flexDirection: `row`,
            justifyContent: `center`,
            gap: '3rem', /* 按需调整两个名字的间距大小 */
          }}>
        <h1 style={{
            color: `white`,
            fontSize: `7vw`,
            margin: 0 /* 清除浏览器默认标题外边距 */
          }}>Gareth</h1>
        <h1 style={{
            color: `white`,
            fontSize: `7vw`,
            margin: 0
          }}>Veale</h1>
        </div>
    </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:45:03