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

如何防止页面宽度缩小时文本溢出背景图像?

如何防止文本在页面缩小时溢出背景图像?

文本溢出背景图像

如图所示,当页面宽度缩小时,如何防止文本溢出背景图像?我希望文本始终与背景图像保持相对位置。

我的HTML代码:

<section class="sec2">
  <h1 class="h1two">A 44-letter alphabet.</h1>
  <h1 class="h1three">A phonetically consistent language.</h1>
  <h1 class="h1four">A determined teacher you can count on.</h1>
</section>

我的CSS代码:

h1 {
  position: relative;
  font-family: "LiberationSansRegular";
  font-style: normal;
  font-weight: 600;
  font-size: 55px;
}

.h1two {
  top: 15%;
}

.h1three {
  top: 30%;
}

.h1four {
  top: 45%;
}

.sec2 {
  height: 30vw;
  background-image: url(pictures/output-onlinepngtools.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  word-break: keep-all;
}

解决方法

1. 给容器添加内边距与溢出控制

通过给背景容器添加内边距,限制文本与容器边缘的距离,同时设置溢出隐藏,确保文本不会超出背景图范围:

.sec2 {
  height: 30vw;
  background-image: url(pictures/output-onlinepngtools.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  word-break: keep-all;
  padding: 2vw; /* 可根据需求调整内边距大小 */
  box-sizing: border-box; /* 确保内边距不会增加容器总宽度 */
  overflow: hidden; /* 隐藏超出容器的内容,若需要滚动可改为auto */
}

2. 使用响应式字体大小

固定字号在小屏幕易溢出,改用clamp()实现自适应字体,兼顾大屏与小屏显示:

h1 {
  position: relative;
  font-family: "LiberationSansRegular";
  font-style: normal;
  font-weight: 600;
  font-size: clamp(24px, 5vw, 55px); /* 最小24px,最大55px,随屏幕宽度自适应 */
}

3. 改用Flexbox优化文本定位

替换相对定位的top值,用Flexbox让文本在容器内垂直均匀分布,布局更稳定:

.sec2 {
  height: 30vw;
  background-image: url(pictures/output-onlinepngtools.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  word-break: keep-all;
  padding: 2vw;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-around; /* 文本垂直均匀分布 */
  overflow: hidden;
}

/* 移除原有的top定位 */
.h1two, .h1three, .h1four {
  top: unset;
}

将以上方案组合使用,即可让文本始终与背景图保持相对位置,不会在页面缩小时溢出。


内容的提问来源于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 09:05:31