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

如何用HTML和CSS在图片指定位置放置文本并适配全屏幕

实现方案

要让文本固定在图片的特定位置且在所有屏幕上位置一致,核心用CSS定位就能实现,具体操作如下:

1. 调整HTML结构

把图片和所有文本放进一个容器中,作为定位的基准容器:

<div class="image-container">
  <img alt="star" src="star.png" />
  <p class="text-item">Text</p>
  <p class="text-item">Text</p>
  <p class="text-item">Text</p>
  <p class="text-item">Text</p>
  <p class="text-item">Text</p>
</div>

2. 添加CSS样式

通过相对定位容器、绝对定位文本,固定文本相对于图片的位置:

/* 容器设为相对定位,作为绝对定位元素的参考基准 */
.image-container {
  position: relative;
  /* 让容器宽度和图片一致,避免多余空白导致定位偏移 */
  display: inline-block;
}

/* 保证图片自适应屏幕,同时比例不变 */
.image-container img {
  width: 100%;
  height: auto;
}

/* 给每个文本单独设置定位,按需调整top/left值匹配目标效果 */
.text-item:nth-child(2) {
  position: absolute;
  top: 15%; /* 距离图片顶部的百分比 */
  left: 25%; /* 距离图片左侧的百分比 */
}

.text-item:nth-child(3) {
  position: absolute;
  top: 35%;
  left: 75%;
}

.text-item:nth-child(4) {
  position: absolute;
  top: 55%;
  left: 20%;
}

.text-item:nth-child(5) {
  position: absolute;
  top: 75%;
  left: 65%;
}

.text-item:nth-child(6) {
  position: absolute;
  top: 90%;
  left: 45%;
}

关键说明

  • 使用百分比单位设置top/left,能确保在不同屏幕尺寸下,文本相对于图片的位置始终一致;如果需要固定像素级位置,也可以替换为px单位,但适配性会有所下降。
  • display: inline-block让容器仅占据图片的宽度,避免容器过宽导致定位偏差。
  • 通过:nth-child选择器可以精准控制每一段文本的位置,完全匹配你想要的布局效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:52:37