Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add another background-image to existing background in css

Tags:

css

Modern browsers allows to add multiple, comma-separated backgrounds to element. For example I can define 2 backgrounds like this:

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?

like image 818
Alexey Ivanov Avatar asked Oct 24 '11 18:10

Alexey Ivanov


2 Answers

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/

like image 62
Alexut Avatar answered Sep 21 '22 21:09

Alexut


@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;
}
like image 36
Andreas Avatar answered Sep 24 '22 21:09

Andreas