CSS - 来自不同规则的多个背景图像

时间:2014-07-25 14:11:31

标签: css background-image

我知道我可以通过在一个语句中声明它们,将多个叠加的背景图像添加到一个元素中,如下所示:

.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做它会更优雅。

1 个答案:

答案 0 :(得分:1)

您的css规则发生冲突,在这种情况下,它会落在文件中,后一条规则优先。要解决这个问题,您需要提高选择器的特异性,并使用组合的background-url属性编写规则。

这正是您在第一个代码段中所拥有的内容,因此""正确"。如果你想在多个选择器中进行,那是不可能的