Mohsen Sarkar
Mohsen Sarkar

Reputation: 6030

How to apply z-index on background-image?

Here is the code :

<div style="background-image: url(/Images/Main/BackMain.png); z-index: 2">
    <div style="background-image: url(/Images/Main/BackMain1.png); z-index: 1">
    </div>
</div>

The above code doesn't show BackMain.png on top of BackMain1.png which is what I'm looking for.

Upvotes: 2

Views: 11816

Answers (2)

SaurabhLP
SaurabhLP

Reputation: 3657

Surely you have to change to html structure for this,

html:-

<div class="container">
<div class="object2"></div>
<div class="object1"></div>
</div>

css:-

.container {
    position: relative;
}


.object1 {
    background-image: url("http://farm8.staticflickr.com/7124/8075023996_f61725fac4_n.jpg");
    height: 280px;
    left: 0px;
    position: absolute;
    top: 0;
    width: 320px;
    z-index: -1;
}

.object2 {
    background-image: url("http://farm9.staticflickr.com/8054/8110021320_ebaa03c9b0_s.jpg");
    background-repeat: no-repeat;
    height: 280px;
    position: absolute;
    width: 320px;
    z-index: 20;
}

Check what i have created:- http://jsfiddle.net/hJbHR/1/

Upvotes: 0

Quentin
Quentin

Reputation: 943571

z-index alters the z position only of positioned elements. If an element is positioned then it will establish a new positioning context and its descendants will be positioned with respect to it.

Consequently, there is no way to set the z-index of an element so it appears in front of any of its descendants.

If you don't position the ancestor at all, and you set the descendant of position: relative; z-index: -1, then you can (in Chrome at least, I haven't tested it further) position the child behind the parent. This is likely to have unwanted side effects though.

Upvotes: 4

Related Questions