2017-01-20 98 views
0

我試圖應用背景圖像漸變在圖像上設置它的父div,但它沒有效果,這是奇怪的,所以我以前這樣做。背景圖像漸變不適用

<header id="hero"> 
    <div id="hero-image"> 
    <a href="#"><img src="http://placeholdit.imgix.net/~text?txtsize=44&txt=Hero%20Image&w=1920&h=500" /></a> 
    </div> 
</header> 

header#hero { 
    margin: 0 auto; 
    width: 100%; 
    font-size: 1rem; 
} 
header#hero #hero-image { 
    background-image: linear-gradient(transparent 50%, black 100%); 
} 
header#hero #hero-image img { 
    display: block; 
    width: 100%; 
    max-height: 500px; 
    object-fit: cover; 
} 

演示:http://codepen.io/ourcore/pen/xgqNZJ

回答

0

我能夠通過應用position: relativez-index: -1#hero-image img來實現這一目標:

header#hero { 
    margin: 0 auto; 
    width: 100%; 
    font-size: 1rem; 
} 
header#hero #hero-image { 
    background-image: linear-gradient(transparent 50%, black 100%); 
} 
header#hero #hero-image img { 
    display: block; 
    position: relative; 
    width: 100%; 
    max-height: 500px; 
    object-fit: cover; 
    z-index: -1; 
} 
0

我會建議通過後臺去做,而不是內嵌圖像作爲objcet-fit沒有按目前還沒有在IE和Edge上工作。漸變和圖像可以使用多背景設置在相同的元素上。

#hero-image { 
 
    height: 200px; 
 
    background: linear-gradient(transparent 50%, black 100%), url("//dummyimage.com/2000x1000") center/cover; 
 
} 
 
#hero-image a { 
 
    display: block; 
 
    height: 100%; 
 
    color: rgba(0,0,0,0); 
 
}
<div id="hero-image"> 
 
    <a href="#">Hidden link text</a> 
 
</div>

編輯

如果圖像需要進行動態添加,你也許可以與在線style="..."屬性做到這一點,或使用<style>...</style>標籤可以放置幾乎無處不在。

+0

我同意,但不幸的是,我不能在我的web應用程序中使用此方法,因爲圖像將由CMS動態插入。 –

+0

@MarioParra您可以使用內聯樣式查看上面的更新信息。 – Stickers

+0

@MarioParra我不知道答案是否有幫助,請標記或評論。 – Stickers