如何在背景色上方添加图片并将图片置于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
相关产品推荐
相关产品推荐

