I have a DIV element with CSS3 perspective on it. The DIV contains 2 child DIVs, and one of these has a translation on the z-axis. This should result in one DIV in front of the other, and so the one in behind should be blocked from view.
However, the visibility of these DIVs seem to be controlled by the order in which they appear in the HTML, instead of being handled automatically by CSS3 perspective.
In the code below, even though #div3 is behind #div2 on the z-axis, it shows up in front because it comes after in the HTML.
I am aware that I can use the z-index
property to explicitly state which DIV should be in front, but again, I'm looking for a more automated method.
<html>
<head>
<style type="text/css">
#div1
{
position: relative;
height: 150px;
width: 200px;
-moz-perspective:150px;
-webkit-perspective:150px;
}
.child
{
padding:50px;
position: absolute;
}
#div2
{
background-color: red;
}
#div3
{
background-color: green;
-moz-transform: translateZ(-50px);
-webkit-transform: translateZ(-50px);
}
</style>
</head>
<body>
<div id="div1">
<div id="div2" class="child">HELLO</div>
<div id="div3" class="child">HELLO</div>
</div>
</body>
</html>
Reference: jsFiddle
Rather than using perspective: 150px;
use transform: perspective(150px);
. Then, also use transform-style: preserve-3d;
so that the z-axis becomes usable.
Here is a reference (with a rotation to help see what is going on): http://jsfiddle.net/joshnh/4DjLP/
And here are the relevant styles:
#div1 {
transform: perspective(150px);
transform-style: preserve-3d;
}