Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

z-index not retained after css3 rotate

Tags:

css

I have this code http://jsfiddle.net/C32Hx/4/

  <style>
  body {margin-left:10px;}
  #top {background:blue;width:30px;height:30px; 
    position:absolute; bottom:0; z-index:2;}
  button {margin-top:200px}
  #back {width:120px;height:100px;background:red; position:absolute}
  #front {width:100px;height:100px;background:green; 
    position:absolute; margin-top:50px; z-index:0.8}
  </style>


  <div id="back"><div id="top"></div> back</div>
  <div id="front">front</div>
  <button onclick="rotate()">rotate</button>


  <script>
  function rotate()
  {
  document.getElementById("back").style.MozTransform = "rotate(10deg)";
  document.getElementById("back").style.WebkitTransform = "rotate(10deg)";
  document.getElementById("back").style.msTransform = "rotate(10deg)";
  document.getElementById("back").style.transform="rotate(10deg)";
  return false;
  }
  </script>

After rotate, z-index is not retained on #top element.

Please suggest how to fix this.

Thanks.

like image 380
Arnold Avatar asked Jul 14 '14 14:07

Arnold


People also ask

Why is Z Index not working CSS?

You set z-index on a static element By default, every element has a position of static. z-index only works on positioned elements (relative, absolute, fixed, sticky) so if you set a z-index on an element with a static position, it won't work.

How do I fix Z index in CSS?

To sum up, most issues with z-index can be solved by following these two guidelines: Check that the elements have their position set and z-index numbers in the correct order. Make sure that you don't have parent elements limiting the z-index level of their children.

Is Z Index inherited CSS?

No, it isn't inherited. You can see it in MDN article. However, be aware that z-index sets the z-position relatively to the stacking context. And a positioned element with non auto z-index will create an stacking context.

Does transform affect Z index?

z-index is canceled by setting transform(rotate)


1 Answers

See http://jsfiddle.net/uR5MS/1/

You have to make the three divs in the same stacking context. It's really unexpected that your code could ever make the blue div above all others, since it's nested to a higher div.

  body {margin-left:10px;}
  #top {background:blue;width:30px;height:30px;position:absolute;bottom:0;z-index:3;top:70px;}
  button {margin-top:200px}
  #back {width:100px;height:100px;background:red;position:absolute; z-index:1}
  #front {width:100px;height:100px;background:green;position:absolute;top:50px; z-index:2;}

You will have to redesign the CSS since the divs are now absolute and in the same stacking level. See that the z-index now is preserved after transforms.

like image 156
Niloct Avatar answered Oct 13 '22 11:10

Niloct