Home > Enterprise >  CSS: How to keep z axis while rotating an element
CSS: How to keep z axis while rotating an element

Time:05-03

I have a rotated circle element and I want to apply an animation to this element so it can get closer. But when I try to apply translateZ to the element, the element moves vertically. And without rotating the element, it actually can get closer when applying translateZ. So I am guessing the z axis is also rotating and the element moves vertically. How can I fix this?

Code is lie below.

html

<div >
  <div >
  </div>
</div>

css

.wrapper {
  width: 300px;
  height: 300px;
  perspective: 400px;
}

.circle {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: black;
  transform: rotateX(60deg);
  animation: moveCircle 1s linear 0s forwards;

  @keyframes moveCircle {
    to {
      transform: rotateX(60deg) translateZ(100px);
    }
  }
}

Expected:

enter image description here

Current:

enter image description here

CodePudding user response:

I think what you want to do is have the circle rotated about its x axis but move its wrapper towards the viewer on the z-axis - the wrapper's z axis still being perpendicular to the screen.

So this snippet sets the perspective on a container, does not animate the circle itself but moves a z translation animation to the wrapper so that will come direct out of the screen and the whole thing 'get closer'.

.container {
  perspective: 400px;
}

.wrapper {
  width: 300px;
  height: 300px;
  transform: translateZ(0px);
  animation: moveWrapper 1s linear 0s forwards;
}

@keyframes moveWrapper {
  to {
    transform: translateZ(100px);
  }
}

.circle {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: black;
  transform: rotateX(60deg);
}
<div >
  <div >
    <div >
    </div>
  </div>
</div>

CodePudding user response:

Is this what you mean?? Let me know

.wrapper {
  width: 300px;
  height: 300px;
  perspective: 400px;
  margin:0 auto;
  padding:50px;
}

.circle {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: black;
  animation: moveCircle 2s linear 0s forwards;
}
  @keyframes moveCircle {
   from {
        transform:scale(.5) rotateX(60deg);        
        
    }
    to {
       transform: scale(1.5) rotateX(60deg);
        
}
  }
<div >
  <div >
  </div>
</div>

  • Related