我知道我可以通过在一条语句中声明它们来将多个叠加的背景图像添加到一个元素,如下所示:
.background1.background2{
background-image: url(background1.png), url(background2.png);
background-position: center, center;
background-repeat: no-repeat, no-repeat;
backgroun-size: 100%, 50%
}
但是,如果我尝试通过多个规则这样做,例如:
.background1{
background-image: url(background1.png);
background-position: center;
background-repeat: no-repeat;
background-size: 100%;
}
.background2{
background-image: url(background2.png);
background-position: center;
background-repeat: no-repeat;
background-size: 50%;
}
然后第二个规则覆盖第一个。有没有一种方法可以通过不同的规则将多个背景图像添加到一个元素,而不会一个覆盖另一个?
我可以通过绝对定位的 div 实现相同的效果,但如果可能的话,我认为通过 css 来实现会更优雅。
最佳答案
您的 css 规则冲突,在这种情况下,它落在文件中的位置,后一条规则优先。要解决这个问题,您需要提高选择器的特异性并使用组合的 background-url 属性编写规则。
这正是您在第一个片段中所拥有的,所以这是“正确的”。如果你想在多个选择器中这样做,那是不可能的
关于CSS - 来自不同规则的多个背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24957754/