CSS 为实现重叠效果,将 margin-top 设为负值时,div 背景被 img 图片遮挡
一、未实现重叠效果
<body>
<img
src="https://cdn.uviewui.com/uview/swiper/swiper2.png"
style="width: 375px;"
alt=""
srcset=""
/>
<div style="width: 375px;height: 80px;background: green;">
<p style="text-align: center;color: #fff;">
CSS 为实现重叠效果,将 margin-top 设为负值时,div 背景被 img 图片遮挡
</p>
</div>
</body>
效果:
二、实现重叠效果,但 div 背景被遮挡
通过将 div margin-top
设为负值实现 div 部分重叠在 img 图片上。
<body>
<img
src="https://cdn.uviewui.com/uview/swiper/swiper2.png"
style="width: 375px;"
alt=""
srcset=""
/>
<div style="width: 375px;height: 80px;background: green; margin-top: -50px;">
<p style="text-align: center;color: #fff;">
CSS 为实现重叠效果,将 margin-top 设为负值时,div 背景被 img 图片遮挡
</p>
</div>
</body>
效果:
由效果图可知,存在 div 的绿色背景被遮挡问题。
三、解决实现重叠效果时 div 背景被遮挡问题
通过将 div 设置为 position: relative;
解决实现重叠效果时 div 背景被遮挡问题。
<body>
<img
src="https://cdn.uviewui.com/uview/swiper/swiper2.png"
style="width: 375px;"
alt=""
srcset=""
/>
<div
style="width: 375px; height: 80px; background: green; margin-top: -50px; position: relative;"
>
<p style="text-align: center;color: #fff;">
CSS 为实现重叠效果,将 margin-top 设为负值时,div 背景被 img 图片遮挡
</p>
</div>
</body>
效果: