Search code examples
htmlcss3dcss-animationscss-transforms

TranslateZ() is ignored for span element


The span element; the child of the div element in the snippet below is behaving unexpectedly. The span element's background-color is set to #0dd and it's transform properties are set to scale( 0.5 ) translateZ( 5rem ). The scale value is respected and shrinks the element to half size; the translateZ value however is ignored and doesn't change the position of the element.

The desired result is for the span element to be pushed forwards away from it's parent div. Why is translateZ ignored here and how can we translate span in the Z direction?

* {
  box-sizing: border-box;
  transform-style: preserve-3d;
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
}
body, span {
  display: flex;
  justify-content: center;
  align-items: center;
}
body {
  perspective: 30rem;
}
section, div, span {
  position: absolute;
  width: 10rem;
  height: 10rem;
}
div, span {
  opacity: 0.5;
  background-color: #000;
}
div span {
  transform: scale( 0.5 ) translateZ( 5rem );
  background-color: #0dd;
}
<style>
  .rotate_y {
    animation-name: rotateY;
    animation-duration: 10s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
  }
  @keyframes rotateY {
    0% {
      transform: rotateY( 0deg );
    }
    100% {
      transform: rotateY( 360deg );
    }  
  }
</style>

<section class='rotate_y'>
  <div>
    <span></span>
  </div>
</section>

UPDATE: Seems to behave properly on IOS. Issue is with desktop Chrome.

enter image description here


Solution

  • The opacity seems to be the culprit but don't know why. It's probably a bug so use transparent background instead:

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      height: 100vh;
      margin: 0;
      perspective: 30rem;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .rotate_y * {
      display: block;
      background-color: rgba(0,0,0,0.5);
      width: 10rem;
      height: 10rem;
      transform-style: preserve-3d;
    }
    
    .rotate_y span {
      transform: scale( 0.5) translateZ( 5rem);
      background-color: rgba(0,221,221,0.5);
    }
    
    .rotate_y {
      transform-style: preserve-3d;
      animation-name: rotateY;
      animation-duration: 10s;
      animation-timing-function: linear;
      animation-iteration-count: infinite;
    }
    
    @keyframes rotateY {
      0% {
        transform: rotateY( 0deg);
      }
      100% {
        transform: rotateY( 360deg);
      }
    }
    <section class='rotate_y'>
      <div>
        <span></span>
      </div>
    </section>