2016-02-01 29 views
3

我有一個父級div.parent,背景色爲白色,div爲圖像。當父級具有背景色時,圖像不顯示爲線性漸變

我設置div.img容器

我需要的是有一個與背景色的容器上的線性梯度:白色,並且圖像上的背景線性梯度。我需要2個「父母」。我不知道我錯過了什麼,它工作正常,當我只有一個DIV ..

.parent{ 
 
    background-color:grey; 
 
} 
 

 
.img-container{ 
 
    height:200px; 
 
    width:200px; 
 
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.30) 0%, rgba(0, 0, 0, 0.75) 100%); 
 
margin:auto; 
 
} 
 

 
.my-img{ 
 
    display:block; 
 
    position:relative; 
 
    width:200px; 
 
    height:200px; 
 
    z-index:-1; 
 
}
<div class="parent"> 
 
    <div class="img-container"> 
 
\t <img class="my-img" src="http://image.noelshack.com/fichiers/2016/05/1454345014-capture-d-ecran-2016-02-01-a-17-43-28.png"> 
 
    </div> 
 
</div>

+1

的圖像沒有顯示,因爲這條線的:。我-IMG {z索引:-1; }你是否想要在圖像頂部有漸變並仍然可以看到圖像? – cocoa

+0

多數民衆贊成那是正確的,我只需要在圖像上的梯度,但我發現我的答案謝謝:) – teddym

回答

3

一個簡單的解決方案,不用搞亂z-index和主要元素/父母的絕對定位,而是使用僞。

這種方式可以很好地處理其餘的內容。

.parent{ 
 
    background-color:grey; 
 
} 
 
.img-container{ 
 
    height:200px; 
 
    width:200px; 
 
    margin:auto; 
 
    position: relative; 
 
} 
 
.img-container:after{ 
 
    content: " "; 
 
    position: absolute; 
 
    left: 0; 
 
    top: 0; 
 
    right:0; 
 
    bottom:0; 
 
    background: linear-gradient(to bottom, rgba(0, 0, 0, 0.30) 0%, rgba(0, 0, 0, 0.75) 100%); 
 
} 
 
.my-img{ 
 
    display:block; 
 
    width:200px; 
 
    height:200px; 
 
}
<div class="parent"> 
 
    <div class="img-container"> 
 
    <img class="my-img" src="http://image.noelshack.com/fichiers/2016/05/1454345014-capture-d-ecran-2016-02-01-a-17-43-28.png"> 
 
    </div> 
 
</div>

+0

謝謝你的男人多數民衆贊成我所需要的,它的作品就像一個魅力。我只是添加了一些Z-索引,因爲我有多個孩子。 – teddym

+0

@teddym不客氣,請接受最合適的答案。 – LGSon

+0

我沒有足夠的聲譽來做到這一點,一旦我有它,我會做到這一點。 – teddym

2

使用position: absolute和應用較低的z-index.parent作爲並列於.my-img

.parent { 
    background-color: grey; 
    z-index: -2; 
    height: 200px; 
    width: 100%; 
    position: absolute; 
} 

.img-container { 
    height: 200px; 
    width: 200px; 
    background: linear-gradient(to bottom, rgba(0, 0, 0, 0.30) 0%, rgba(0, 0, 0, 0.75) 100%); 
    margin: auto; 
} 

.my-img { 
    display: block; 
    position: relative; 
    width: 200px; 
    height: 200px; 
    z-index: -1; 
} 

查看it out。