CSS 為實作重疊效果,將 margin-top 設為負值時,div 背景被 img 圖片遮擋
一、未實作重疊效果
<body>
<img
src="https://img.uj5u.com/2023/03/24/344226241206411.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://img.uj5u.com/2023/03/24/344226241206411.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 的綠色背景被遮擋問題,這時如果通過z-index來設定層疊順序是無效的,
三、解決實作重疊效果時 div 背景被遮擋問題
方法一、div 設定 position: relative;
通過將 div 設定為 position: relative; 解決實作重疊效果時 div 背景被遮擋問題,
<body>
<img
src="https://img.uj5u.com/2023/03/24/344226241206411.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>
效果:

方法二、div 設定 display: inline-block;,并設定父容器寬度
<body style="width: 375px;">
<img
src="https://img.uj5u.com/2023/03/24/344226241206411.png"
style="width: 375px;"
alt=""
srcset=""
/>
<div
style="width: 375px;height: 80px;background: green; margin-top: -50px; display: inline-block;"
>
<p style="text-align: center;color: #fff;">
CSS 為實作重疊效果,將 margin-top 設為負值時,div 背景被 img 圖片遮擋
</p>
</div>
</body>
上述代碼中,同時設定了父容器 body 的寬度和 div 的 display: inline-block;,
效果:

方法三、div 設定position: absolute; top: 100px;,并去除margin-top: -50px;,同時設定父容器position: relative;
<body style="position: relative;">
<img
src="https://img.uj5u.com/2023/03/24/344226241206411.png"
style="width: 375px;"
alt=""
srcset=""
/>
<div
style="width: 375px;height: 80px;background: green; position: absolute; top: 100px;"
>
<p style="text-align: center;color: #fff;">
CSS 為實作重疊效果,將 margin-top 設為負值時,div 背景被 img 圖片遮擋
</p>
</div>
</body>
上述代碼中,同時設定父容器 body 的position: relative;和 div 的position: absolute; top: 100px;,并去除了 div 的margin-top: -50px;,
效果:

作者:飛仔FeiZai
出處:https://www.cnblogs.com/yuzhihui/p/17246928.html
宣告:歡迎任何形式的轉載,但請務必注明出處!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/547957.html
標籤:其他
上一篇:vue前端匯出excel
