Can css3 translateZ() be used instead of z-index?
Asked Answered
R

2

22

For example having 2 div's positioned absolute, one can put first div upon second by setting first div's z-index higher than second one's. Can we achieve such behaviour using translateZ() or translate3d?

Rotberg answered 31/7, 2013 at 17:38 Comment(0)
F
24

The answer now, 3 years after, is that you can. You need to use transform-style: preserve-3d; on the parent, but it's possible.

.container {
  transform-style: preserve-3d;
}
.test1 {
  width: 500px;
  height: 500px;
  background: red;
  transform: translate3d(0, 0, 1px);
}
.test2 {
  width: 500px;
  height: 500px;
  background: green;
  left: 250px;
  top: 250px;
  position: absolute;
  transform: translate3d(0, 0, 0);
}
<div class="container">
  <div class="test1">
    test
  </div>

  <div class="test2">
    test #2
  </div>
</div>
Finagle answered 7/4, 2016 at 11:28 Comment(6)
Thanks, marked this answer as accepted. It is worth noting that both envolved elements should have transform property applied.Rotberg
Hey. Can you take a look at this? The button is hidden despite having greater translate z value. Thanks.Winnifredwinning
Hm. I’m getting a big red square in Chrome 58 and Safari 10.1.Disoblige
Oh, wait. Is that what I’m meant to get?Disoblige
Yeah, that's how it was defined... :)Finagle
FYI: this doesn't seem to work if .container has overflow: hidden; appliedRally
T
5

Short answer: No. View demo which works as of time of posting

Longer answer: It's not supposed to, but sometimes, such as when one element has a transform when its sibling doesn't, some browsers don't handle the situation well, resulting in the z-index being ignored.

Generally, however, this is because the transform itself is applied, not because of the translateZ. The solution in such a case it to give all relevant elements transform: translate3d(0px, 0px, 0px) or something similar which makes the browser render the elements more carefully

Taima answered 24/1, 2014 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.