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

如何让div内文本在图片上均匀分布且页面缩放时不溢出

解决思路与代码修改

问题核心

原方案用position: absolute+固定top百分比定位文本,但未将定位基准绑定到图片容器,导致页面缩小时文本脱离图片范围;同时固定字号在小屏幕下易溢出。

修改后的HTML代码

<!-- mountain background -->
<div class="container">
  <div class="item2">
    <div class="text-container">
      <h2 class="mtn1">A 44-letter alphabet.</h2>
      <h2 class="mtn2">
        A phonetically <br />
        consistent language.
      </h2>
      <h2 class="mtn3">
        A determined teacher <br />
        you can count on
      </h2>
    </div>
    <img
      class="img4"
      src="pictures/output-onlinepngtools.png"
      alt=""
    />
  </div>
  <!-- mountain end -->
</div>

修改后的CSS代码

/* mountain photo */
.img4 {
  height: auto;
  width: 100%;
  min-height: 400px;
  display: block; /* 移除图片默认行内间距 */
}

.container {
  width: 100vw;
  position: absolute;
  display: flex;
  flex-wrap: wrap;
}

.item2 {
  width: 100vw;
  position: relative; /* 设置为相对定位,作为内部绝对定位元素的基准 */
}

.text-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly; /* 垂直方向均匀分布文本 */
  padding: 2rem; /* 给文本留边距,避免贴边 */
  box-sizing: border-box; /* 内边距计入容器宽度,防止溢出 */
}

.mtn1, .mtn2, .mtn3 {
  text-align: left;
  font-family: "LiberationSansRegular";
  font-style: normal;
  font-size: clamp(2rem, 5vw, 4.5rem); /* 响应式字号,小屏幕自动缩小 */
  max-width: 100%; /* 文本不超出容器宽度 */
  margin: 0; /* 移除h2默认外边距 */
}

关键调整说明

  • 给.item2加position: relative,让文本的绝对定位以图片容器为基准,彻底避免脱离图片范围。
  • 用.text-container的flex布局替代固定top百分比,通过justify-content: space-evenly自动实现文本垂直均匀分布,无需硬编码位置。
  • 用clamp()设置响应式字号,兼顾大屏显示效果和小屏幕适配,从根源解决文本溢出问题。
  • 添加内边距和box-sizing: border-box,保证文本不会贴紧图片边缘,同时避免内边距导致容器宽度溢出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:48:25