我遇到的问题是在HTML中内联设置背景图像(因为它是来自数据库的动态图像src),但是我仍然想在现有背景图像之上添加半透明渐变。
不使用JS完全有可能吗?
div {
width: 200px;
height: 200px;
background-repeat: no-repeat;
background-size: cover;
background-image: linear-gradient(to bottom, rgba(0, 0, 0, .6), rgba(0, 0, 0, .2)); /* I need this to be added **on top** of the existing background image */
}
<div style="background-image: url(//lorempixel.com/1920/1080/nature/)"></div>
不,background-image
如果通过内联样式设置了一个,则不能通过CSS添加另一个。但是您可以使用伪元素并将其放置在的顶部div
。
注意:正如Mike在评论中所指出的那样,使用:before
元素比使用元素要好得多,:after
因为将元素:after
置于其他所有元素之上,并且需要z-index
对其他元素进行大量设置来克服它(可能会变得乏味) 。除了此设置外pointer-events:none
,伪元素也将有所帮助。
div {
position: relative;
width: 200px;
height: 200px;
}
div:before {
position: absolute;
content: '';
height: 100%;
width: 100%;
top: 0;
left: 0;
background-repeat: no-repeat;
background-size: cover;
background-image: linear-gradient(to bottom, rgba(0, 0, 0, .6), rgba(0, 0, 0, .2));
pointer-events: none;
}
div * {
position: relative;
}
a, p, span {
color: red;
}
<div style="background-image: url(//lorempixel.com/1920/1080/nature/)">
<a href='#'>Some link for hit test</a>
<p>Some paragraph to test the color being affected by gradient on top or not</p>
<span>Some span to test the color being affected by gradient on top or not</span>
</div>
可以使用CSS将多个背景图像添加到单个元素,但是像其他属性一样,声明不是可加的,因此图像和渐变都应通过CSS(或)通过后端设置。
下面是一个示例代码段,其中渐变和图像均已内联设置。您可以将整个值存储为字符串在DB中(或在设置内联样式时附加它)(使用JS或后端程序)。
div {
position: relative;
width: 200px;
height: 200px;
}
a, p, span {
color: red;
}
<div style="background-image: url(//lorempixel.com/1920/1080/nature/), linear-gradient(to bottom, rgba(0, 0, 0, .6), rgba(0, 0, 0, .2))">
<a href='#'>Some link for hit test</a>
<p>Some paragraph to test the color being affected by gradient on top or not</p>
<span>Some span to test the color being affected by gradient on top or not</span>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句