Search code examples
htmlcsscss-transforms

How can I transform a div to a tilted perspective?


I'm trying to transform my div like the green box.

enter image description here

I want to get 3D transform, not mask :

enter image description here

I find a way with this generator but the css code doesn't work on my fiddle:

/*transform css3*/ 
#screen { 
    transform: scale(1.0) scaleZ(1.0) rotateX(-16deg);
    transform-origin: 0% 0%;
    perspective: 450;
    perspective-origin: 100% 50%;
}

enter image description here

body {
    height:100%;
    padding:0;
    margin:0;
}

#mask {
    background:url(https://i.sstatic.net/cBK0O.png) no-repeat;
    background-size:350px;
    height:200px;
    position:relative;
}

#screen:hover {
    background:url(https://www.actugaming.net/wp-content/uploads/2018/06/Assassins-Creed-Odyssey_Leak_06-10-18_015-1.jpg);
    background-size:100%;
}

#screen {
    position:absolute;
    bottom:38px;
    background:red;
    opacity:0.6;
}
   
#screen { 
    left:70px;
    width:240px;
    height:calc(240px * 9 / 16); /*keep 16/9 !*/
}

/*transform css3*/ 
#screen { 
    transform: scale(1.0) scaleZ(1.0) rotateX(-16deg);
    transform-origin: 0% 0%;
    perspective: 450;
    perspective-origin: 100% 50%;
}
<div id="mask">
<div id="screen"></div>
</div>


Solution

  • You need rotation and also a perspective to have the bottom right as origin. Note that perspective need to be applied to a parent element:

    .box {
      display:inline-block;
      perspective-origin:bottom right;
      perspective:100px;
    }
    
    img {
      margin:30px 50px;
      transform:rotateX(-8deg);
      width:250px;
    }
    <div class="box">
    <img src="https://www.actugaming.net/wp-content/uploads/2018/06/Assassins-Creed-Odyssey_Leak_06-10-18_015-1.jpg" >
    </div>

    Or use perspective inside the transform and adjust the origin of transform not origin of perspective:

    img {
      margin: 30px 50px;
      transform: perspective(100px) rotateX(-8deg);
      width: 250px;
      transform-origin: bottom right
    }
    <div class="box">
      <img src="https://www.actugaming.net/wp-content/uploads/2018/06/Assassins-Creed-Odyssey_Leak_06-10-18_015-1.jpg">
    </div>