[英]How to add another background-image to existing background in css
Modern browsers allows to add multiple, comma-separated backgrounds to element. 现代浏览器允许向元素添加多个以逗号分隔的背景。 For example I can define 2 backgrounds like this: 例如,我可以像这样定义2个背景:
background: url(image1.png) no-repeat left top, url(image2.png) no-repeat right bottom;
It's works wonderfull, and all, but there is often a situation then I want to have one background always applied on element, and another only then I add second class or some modificator. 它的工作很精彩,而且一切都很好,但是经常出现这种情况,我希望有一个背景总是应用于元素,而另一个只有我添加第二个类或一些修饰符。 For example I want following code: 例如,我想要以下代码:
<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>
...to return element with both background applied (code above will return only second). ...返回应用了两个背景的元素(上面的代码只返回第二个)。
Is there a way in modern css to add second one without fully copy the first one in it? 在现代css中有没有办法添加第二个而不完全复制第一个?
You can do this with an pseudo-element like after or before and adding a wrap to the element. 您可以使用像之后或之前的伪元素并向元素添加包装来执行此操作。
.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>
Here is the jsfiddle: http://jsfiddle.net/alexut/jz0pm47t/1/ 这是jsfiddle: http : //jsfiddle.net/alexut/jz0pm47t/1/
@Jason @Jason
This code will not work. 此代码无效。 You have to use this 你必须使用它
.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;
}
I know you don't want to fully copy anything but I would do something like this 我知道你不想完全复制任何东西,但我会做这样的事情
.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;
}
where the second class basically "overwrites" the first class. 第二类基本上“覆盖”第一类。
The other option is to use a dynamic stylesheet language like LESS ( http://lesscss.org/ ), where you can use variables. 另一种选择是使用动态样式表语言,如LESS( http://lesscss.org/ ),您可以在其中使用变量。
In LESS, you could do something like this 在LESS,你可以做这样的事情
@twoBackgrounds: url(image1.png) no-repeat left top;
.one{
@twoBackgrounds;
}
.two{
@twoBackgrounds,
background: url(image2.png) no-repeat right bottom;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.