我试图通过在父级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;
}
答案 0 :(得分:0)
我通过将position: relative
和z-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;
}
答案 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>
标记,它几乎可以放在任何地方。