Search code examples
htmlcssimageperspective

CSS- Applying perspective while rotating an img in css


I'm trying to apply perspective while rotating animation is on in CSS.

However, it works in either way only like

rotating is working only or perspective is working only as below. this one or

.vinyl {
    width: 200px;
    display: block;
    margin: auto;
    opacity: 0.8;
    transform: rotate3d(1,0,0,45deg)
}

this one

.vinyl {
    width: 200px;
    display: block;
    margin: auto;
    opacity: 0.8;
/*     transform: rotate3d(1,0,0,45deg); */
    animation: rotation 2s infinite linear; 
}

how do I apply rotation animation and perspective at the same time? as if the image is rotating and the viewer is watching it with a perspective.

Full code link is in the following link.

.vinyl {
    width: 200px;
    display: block;
    margin: auto;
    opacity: 0.8;
/*     transform: rotate3d(1,0,0,45deg); */
    animation: rotation 2s infinite linear; 
}

.container{
transform-style: preserve-3d;
perspective: 350px;
}

@keyframes rotation {
    from {
        -webkit-transform: rotate(0deg);
    }
    to {
        -webkit-transform: rotate(359deg);
    }
}
<div class="container">
<img class = 'vinyl' src="https://picsum.photos/seed/picsum/200/300" alt="">
</div>


Solution

  • Keep using your 3D transformation inside the animation:

    .vinyl {
      width: 200px;
      display: block;
      margin: auto;
      opacity: 0.8;
      animation: rotation 2s infinite linear;
    }
    
    .container {
      transform-style: preserve-3d;
      perspective: 350px;
    }
    
    @keyframes rotation {
      from {
        transform: rotate3d(1, 0, 0, 45deg) rotate(0);
      }
      to {
        transform: rotate3d(1, 0, 0, 45deg) rotate(360deg);
      }
    }
    <div class="container">
      <img class='vinyl' src="https://picsum.photos/seed/picsum/200/300" alt="">
    </div>