Rotating parent div in perspective without affecting inner div [duplicate]
From the specification:
By default, transformed elements do not create a 3D rendering context and create a flattened representation of their content. However, since it is useful to construct hierarchies of transformed objects that share a common 3-dimensional space, this flattening behavior may be overridden by specifying a value of
preserve-3d
for thetransform-style
property. This allows descendants of the transformed element to share the same 3D rendering context.
So simply add transform-style:preserve-3d
to the subcontainer element and the perspective of the grand-parent will be respected:
.container{
background: #f4f7be;
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
perspective: 1000px;
}
.subcontainer{
background: #baf7f6;
width: 70%;
height: 70%;
display: flex;
justify-content: center;
align-items: center;
transform: scale(1.001);
transform-style:preserve-3d;
}
.shape{
background: #555;
width: 40%;
height: 50%;
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
transform: translateZ(300px);
}
<html>
<div class="container">
<div class="subcontainer">
<div class="shape"></div>
</div>
</div>
</html>
So, is perspective: 500px in the parent equivalent to transform: perspective(500px) in the child?
Not exactly equivalent because you need to consider other factors like the parent dimension, transform-origin, perspective-origin, etc
A trivial example:
.box {
padding: 20px;
border: 1px solid;
}
.box>div {
width: 100px;
height: 100px;
background: red;
}
<div class="box" style="perspective:100px;">
<div style="transform:translateZ(10px);"></div>
</div>
<div class="box">
<div style="transform:perspective(100px) translateZ(10px);"></div>
</div>
The difference is due to the origin. In the first case, the perspective will use the center of the parent as origin (because perspective-origin
is center by default). In the second case, the center of the element will be used as origin (because transform-origin
is center by default)
Related questions for more detail and examples:
perspective and translateZ moves diagonally
Why perspective isn't giving the same result when some styles are updated?
CSS 3d transform doesn't work if perspective is set in the end of property