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

如何在图片上方居中显示文本块?CSS布局问题求助

问题核心原因

你CSS里的父容器选择器写错了——HTML中父容器的id是top-of-page,但你写的是#haut-de-page,这导致父容器没有被设置为position: relative,所以#text-block的绝对定位会相对于<body>而非图片的父容器,最终跑到图片下方。

解决思路与代码示例

方法一:修复绝对定位实现居中

先修正选择器,再通过绝对定位+transform实现水平垂直居中:

<body>
   <div id="top-of-page">
     <img src="images/etudes.png">
     <div id="text-block">
       <h1>Title</h1>
     </div>
   </div>
</body>
#top-of-page {
  position: relative;
  margin: 10px;
  width: 100%;
}

#top-of-page img {
  width: 100%;
  display: block; /* 消除图片默认底部间隙 */
}

#text-block {
  position: absolute;
  /* 垂直水平居中核心代码 */
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  
  background-color: rgba(0, 0, 0, .5);
  color: white;
  padding: 20px;
  text-align: center; /* 可选:让文本块内文字居中 */
}

方法二:Flex布局实现(更简洁推荐)

无需绝对定位,通过父容器的Flex属性直接让文本块居中在图片上方:

<body>
   <div id="top-of-page">
     <img src="images/etudes.png">
     <div id="text-block">
       <h1>Title</h1>
     </div>
   </div>
</body>
#top-of-page {
  position: relative;
  margin: 10px;
  width: 100%;
  /* Flex居中核心 */
  display: flex;
  align-items: center;
  justify-content: center;
}

#top-of-page img {
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例 */
}

#text-block {
  position: relative;
  z-index: 1; /* 确保文本块在图片上方 */
  background-color: rgba(0, 0, 0, .5);
  color: white;
  padding: 20px;
  text-align: center;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 19:26:16