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

如何让图片上方的文本框在页面缩放时保持固定位置?

解决文本框随页面缩放保持相对图片位置的问题

嘿,这个问题我之前也碰到过!你现在用的是固定像素值的绝对定位,当页面缩放或者屏幕尺寸变化时,这些固定的top和left就没法和图片保持相对位置了——毕竟像素是固定的,而图片的尺寸会跟着页面缩放变化对吧?

核心思路:让文本框相对于图片容器定位,用百分比替代固定像素

我们需要把文本框的定位基准从整个页面,改成和图片同尺寸的容器,然后用百分比来设置位置和尺寸,这样缩放时所有元素都会按比例变化,自然就能保持相对位置了。

修改后的代码示例

CSS部分

#container {
  position: relative;
  width: 50%; /* 和图片原来的宽度保持一致 */
  margin: 0 auto; /* 让容器居中,和图片的居中效果匹配 */
}

.center {
  display: block;
  width: 100%; /* 图片占满容器宽度,保证容器和图片尺寸同步 */
  height: auto; /* 保持图片的原始宽高比,避免拉伸变形 */
}

#example {
  color: white;
  position: absolute;
  /* 用百分比替代固定像素,数值是原来的像素值除以图片的宽/高 */
  top: 11.7%; /* 50px ÷ 428px(图片高度)≈ 11.7% */
  left: 89.7%; /* 680px ÷ 758px(图片宽度)≈ 89.7% */
  width: 39.6%; /* 300px ÷ 758px ≈ 39.6% */
  height: 11.7%; /* 50px ÷ 428px ≈ 11.7% */
  padding: 5px;
  background-color: transparent;
}

#example2 {
  color: white;
  position: absolute;
  top: 28%; /* 120px ÷ 428px ≈ 28% */
  left: 122.7%; /* 930px ÷ 758px ≈ 122.7% */
  width: 39.6%;
  height: 11.7%;
  padding: 5px;
  background-color: transparent;
}

#example3 {
  color: white;
  position: absolute;
  top: 46.7%; /* 200px ÷ 428px ≈ 46.7% */
  left: 96.3%; /* 730px ÷ 758px ≈ 96.3% */
  width: 39.6%;
  height: 11.7%;
  padding: 5px;
  background-color: transparent;
}

HTML部分(无需大改,保持原有结构即可)

<div id="container">
  <div id="example">I am Training | Apr 16 – Jun 15<br> 60 days</div>
  <div id="example2">Compliance |<br> Jun 11 – Jul 11</div>
  <div id="example3">Harassment Free<br> Work May 11</div>
  <img class="center" src="https://dummyimage.com/758x428/000/fff" />
</div>

关键修改点解释

  1. 容器#container:设置和图片一致的宽度并居中,因为position: relative,它会成为文本框的定位基准。
  2. 图片样式:改为width:100%和height:auto,确保图片始终占满容器,同时保持原始宽高比,避免拉伸变形。
  3. 文本框的定位和尺寸:把所有固定像素值转换成相对于容器宽高的百分比——计算方式是「目标像素值 ÷ 图片原始宽/高」,这样页面缩放时,文本框的位置和大小会跟着容器(也就是图片)按比例缩放,完美保持相对位置。

如果需要更精确的微调,你可以稍微调整百分比的小数点后数值,或者结合calc()来混合百分比和小像素值(比如left: calc(89.7% + 5px))。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:54:40