以下 HTML 标记按预期静态呈现。
style='background: linear-gradient(to right, rgba(255,255,255,0) 20%, rgba(255,255,255,1) 30%, rgba(255,255,255,1)), url(<%= image_path "/bg/#{@this_area.id}.svg" %>);'>
但是,由于这是由变量动态管理的,并且目标是添加
@keyframes moveBg {
to {
background-position: 100% 0;
}
}
我试图执行以下操作
<div class='bg_x' style='background: url(<%= image_path "/bg/#{@this_area.id}.svg" %>);'>
并定义类
.bg_x {
background: linear-gradient(to right, rgba(255,255,255,0) 20%, rgba(255,255,255,1) 30%, rgba(255,255,255,1))
animation: moveBg 20s linear infinite;
}
但是,使用类和内联定义无法将渐变与背景图像集成(甚至在添加动画之前(。 因此,内联覆盖了类,即使指令是互补的。
由于CSS文件不能接受变量,是否可以部分不内联地实现这种所需的效果?
由于CSS 中的级联,内联确实推翻了类。绝非如此。线性渐变是background-image
属性的一部分(如果您想组合多个样式,就像margin-left
和margin
一样,则background
速记(。通常,您可以将background-color
和background-image
或其他元素分开,但是对于linear-gradient()
,这是不可能的,因为它们都使用background-image
属性太糟糕了。
在下面的示例中,您可以找到我找到的两个解决方案。希望这可以帮助您解决此问题。
/* ClassBased */
.bg_classBased {
position: relative;
}
.bg_classBased:before {
content: "";
position: absolute;
top: 0;
left: 0;
z-index: 1;
background: linear-gradient(to right, rgba(255,255,255,0) 20%, rgba(255,255,255,1) 30%, rgba(255,255,255,1));
width: 100%;
height: 100%;
}
/* Animation */
.bg_x {
animation: moveBg 20s linear infinite;
}
@keyframes moveBg {
to {
background-position: 100% 0;
}
}
/* misc styling */
div {
padding: 40px;
}
<h1>Inline based</h1>
<div class="bg_x" style='background: linear-gradient(to right, rgba(255,255,255,0) 20%, rgba(255,255,255,1) 30%, rgba(255,255,255,1)), url("https://placehold.it/100x100");'></div>
<h1>Classbased</h1>
<div class="bg_x bg_classBased" style='background: url("https://placehold.it/100x100");'></div>