I am currently working on a site in which I need hearts. I create the hearts using JavaScript and CSS:
function heart(x, y, pos, width, r) {
var height = width + (width / 2 + 1);
var heart = "position:" + pos + ";left:" + x + "px;top:" + y + "px;width:" + width + "px;height:" + height + "px;transform: rotate(" + r + "deg);-moz-transform: rotate(" + r + "deg);-webkit-transform: rotate(" + r + "deg);";
var slices = "left:" + width + "px;width:" + width + "px;height:" + height + "px";
$("body").append('<div class="heart" style="' + heart + '"><div class="slice" style="' + slices + '"></div><div class="slice2" style="' + slices + '"></div></div>');
}
I'm currently trying to put a large heart under a box using:
heart(282, 69, "absolute", 230, 0);
However, z-index is not doing anything, as you can see in my JSFiddle example.
I've even tried setting the z-index of the universal selector (*) to 0 while changing the z-index of the box to 10 !important; but that didn't work either. I am puzzled about why this is happening, but I'm pretty sure it has to do with the dynamic heart. Thank you.
An element needs to be positioned in order for the z-index to work. See the visual formatting modal.
In this instance, you could simply add position:relative to the box.
.welcome {
z-index:10;
position: relative;
background: #fff;
margin: 0 auto;
width: 200px;
padding: 100px;
text-align: center;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 3px;
-moz-box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 3px;
box-shadow: rgba(0, 0, 0, 0.2) 0px 1px 3px;
}
No need for !important either.
In order to use z-index, your <div>s can't be position: static; (which is the default)
So in order to display the .welcome above the hearts you need to add position:relative;
Then it should work.
Your z-index is not working because your .welcome box has a static positioning, so your
.welcome { z-index: 10 !important }
declaration is not having any effect. Because of this, the hearts, that have z-index:0, will still be on top.
To fix this, either
a) set the hearts to z-index: -1
.heart { z-index: -1 }
b) set .welcome's position to something different than it's initial static position.
.welcome { position: relative }
And lose the !important, that's bad practice.
来源:https://stackoverflow.com/questions/22394432/the-z-index-property-is-not-behaving-as-expected