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

如何在背景色上方添加图片并将图片置于div底部?

解决方案

方法一:优化背景属性修复原代码

你的代码未生效通常是因为背景图片尺寸与容器不匹配,导致图片显示不全或被挤出可视区域。调整以下属性即可解决:

.teal {
  text-align: center;
  padding: 40px;
  background-color: #2dd5c4;
  background-image: url("https://www.w3schools.com/html/pic_trulli.jpg");
  background-repeat: no-repeat;
  background-position: bottom center; /* 水平居中+垂直靠底 */
  background-size: contain; /* 保持图片比例完整显示 */
  min-height: 220px; /* 给容器设置最小高度,预留图片显示空间 */
  /* 若希望图片忽略padding贴紧容器底部,添加此行:background-origin: content-box; */
}
<div class="teal">
  <h3>Lorem ipsum dolor sit amet</h3>

  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo l. igula eget dolor. Aenean massa. <br />
    <button> Call to action</button></p>
</div>

方法二:伪元素实现精准定位(推荐)

如果需要图片完全贴合div底部(不受padding影响),用:after伪元素能更灵活控制:

.teal {
  text-align: center;
  padding: 40px;
  background-color: #2dd5c4;
  position: relative; /* 作为伪元素的定位参考 */
  min-height: 220px;
}

.teal:after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 70px; /* 自定义图片显示高度 */
  background-image: url("https://www.w3schools.com/html/pic_trulli.jpg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover; /* 图片铺满宽度,自动裁剪高度 */
}
<div class="teal">
  <h3>Lorem ipsum dolor sit amet</h3>

  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo l. igula eget dolor. Aenean massa. <br />
    <button> Call to action</button></p>
</div>

核心提示

  • background-size: contain会完整保留图片比例,cover会让图片铺满容器但可能裁剪边缘,按需选择。
  • 伪元素方案中,父容器必须设置position: relative,否则伪元素会相对于整个页面定位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:16:01