如何在css中将另一个背景图像添加到现有背景中

时间:2011-10-24 18:07:55

标签: css

现代浏览器允许为元素添加多个以逗号分隔的背景。例如,我可以像这样定义2个背景:

background: url(image1.png) no-repeat left top, url(image2.png) no-repeat right bottom;

它的工作很精彩,而且一切都很好,但是经常出现这种情况我希望有一个背景总是应用于元素,另一个只有我添加第二个类或一些修饰符。例如,我想要以下代码:

<style>
    .one { background: url(image1.png) no-repeat left top; }
    .two { background: url(image2.png) no-repeat right bottom;}
</style>

<div class="one two"></div>

...返回应用了两个背景的元素(上面的代码只返回第二个)。

现代css中有没有办法添加第二个而不完全复制第一个?

3 个答案:

答案 0 :(得分:3)

您可以使用像之前或之后的伪元素并为元素添加包装来执行此操作。

.wrap {
    width:500px;
    height: 500px;
    border:1px solid red;
    position:relative;
}
.one {  
    width:100%;height:100%;
    background-image: url(http://dummyimage.com/250x250/dfdbb9/dfdbb9.png);
    background-repeat:no-repeat;
    background-position:left top;
}
.two:after {    
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    top:0;
    left:0;
    z-index: -1;   
    background-image:  url(http://dummyimage.com/250x250/b9d9df/b9d9df.png);
    background-repeat:no-repeat;        
    background-position:right bottom;
}
<div class="wrap">
    <div class="one two"></div>
</div>

这是jsfiddle:http://jsfiddle.net/alexut/jz0pm47t/1/

答案 1 :(得分:2)

@Jason

此代码无效。你必须使用这个

.one {
  background: url(image1.png) no-repeat left top;
}

.two {
  background: url(image1.png) no-repeat left top, url(image2.png) no-repeat right bottom;
}

答案 2 :(得分:0)

我知道你不想完全复制任何东西,但我会做这样的事情

.one{ 
    background: url(image1.png) no-repeat left top; 
    }

.two{
    background: url(image1.png) no-repeat left top, 
    url(image2.png) no-repeat right bottom;
}

其中第二类基本上“覆盖”第一类。

另一种选择是使用动态样式表语言,如LESS(http://lesscss.org/),您可以在其中使用变量。

在LESS,你可以做这样的事情

@twoBackgrounds: url(image1.png) no-repeat left top;

.one{ 
    @twoBackgrounds;
    }

.two{
    @twoBackgrounds, 
    background: url(image2.png) no-repeat right bottom;
}