有一個div容器:
<div class="background-test"></div>
場景:div容器的背景頭部是一張圖,其餘的地方用背景色填充,這個div容器要隨內容撐大,所以不能設置成position:absolute,直接像下面這樣設置樣式的話:
background:url(*****) 顏色值;
如果背景圖是png格式,有些透明的地方就顯示出來上面設置的 顏色值 出來,這樣和設計師設計的稿子不符,所以可以用以下樣式設置:
.background-test{
position: relative;
height:auto;
width:100%;
background:url('https://p1.meituan.net/1440.590/codeman/d2ab674fa0e4c875865e524d82fe15a34372569.png') no-repeat;
color:#000
}
.background-test::before{
content:'';
background-color:pink;
position:absolute;
color:#fff;
bottom:0;
top:590px;
left:0;
right:0;
z-index:-1;
height:auto;
width:100%;
}
給這個div設置僞元素,記得設置position:absolute;top:590px;z-index:-1;,其中top:590px是爲了給背景圖空出位置,z-index:-1是防止僞類層在div容器之上,覆蓋div的內容。