如何实现类似示例图的图片后方蓝色背景条效果?
实现图片后方添加蓝色背景条的方案
当然可以实现你要的效果,先梳理下你现有代码的问题:
- 图片被嵌套在高度仅125px的
.line-divider容器中,但图片高度设为300px,会导致图片溢出容器,布局混乱 - 内联样式覆盖了
.line-divider的蓝色背景,改成了红色,不符合需求
下面给你两种可行的实现方案:
方案一:用伪元素实现(无需额外DOM节点)
这种方式不需要新增HTML元素,利用父容器的伪元素生成蓝色背景条,让它处于图片后方:
<div class="image-with-bar"> <img src="https://dfstudio-d420.kxcdn.com/wordpress/wp-content/uploads/2019/06/digital_camera_photo-1080x675.jpg" alt="示例图片" height="300px" > </div>
.image-with-bar { position: relative; display: inline-block; /* 容器宽度自动适配图片 */ } .image-with-bar::after { content: ""; position: absolute; bottom: 0; /* 让背景条紧贴图片底部 */ left: 0; width: 100%; height: 125px; background-color: #29334B; z-index: -1; /* 确保背景条在图片后方 */ }
如果想要背景条部分被图片覆盖,只需要把bottom的值改成负数,比如bottom: -25px即可。
方案二:新增DOM元素实现
如果需要更灵活的样式控制,可以单独添加一个div作为背景条:
<div class="image-container"> <img src="https://dfstudio-d420.kxcdn.com/wordpress/wp-content/uploads/2019/06/digital_camera_photo-1080x675.jpg" alt="示例图片" height="300px" > <div class="blue-bar"></div> </div>
.image-container { position: relative; display: inline-block; } .blue-bar { position: absolute; bottom: 0; left: 0; width: 100%; height: 125px; background-color: #29334B; z-index: -1; }
关键要点说明
- 父容器设置
position: relative,是为了让子元素(或伪元素)的绝对定位基于该容器 z-index: -1是核心,保证蓝色背景条处于图片的后方层级- 通过调整
bottom属性,可以自由控制背景条与图片的位置关系
内容的提问来源于stack exchange,提问作者Erbi Silva
相关产品推荐
相关产品推荐

