In the example below, I have demonstrated the current behavior I am experiencing and the desired outcome.
// Rotated div
rotated.style.left = "50px";
rotated.style.top = "100px";
// Original "untouched" div
original.style.left = "50px";
original.style.top = "100px";
// Where the rotated div *should* be
expected.style.left = "-10px";
expected.style.top = "160px";
div {
position: absolute;
height: 80px;
width: 200px;
opacity: 0.5;
mix-blend-mode: overlay;
}
#rotated {
transform: rotateZ(90deg);
background: blue;
}
#original {
background: red;
}
#expected {
transform: rotateZ(90deg);
background: green;
}
<div id="rotated"></div>
<div id="original"></div>
<div id="expected"></div>
The red div represents the "original" div without any transformations applied. The blue div is rotated by 90 degrees but their corners do not align as expected. The green div shows the correct position where the blue div should be.
It is evident that the left
and top
properties are not working as intended. While I am aware of the issue, I am seeking solutions or alternatives. I have come across the transform-origin
property but faced challenges in its implementation due to dynamically created elements with unknown dimensions that may change over time.
For this specific example, adding transform-origin: 40px 40px;
to the div#rotated
element resolves the issue. However, replicating this for multiple elements and adapting it to changing dimensions is not practical in my project.
I am exploring two potential solutions:
A CSS-based approach that dynamically calculates the element's height to determine the transform-origin (or any CSS solution that works effectively)
Using JavaScript to compute the accurate position (e.g.,
-10, 160
) whenever an element needs to be moved
--- update ---
This challenge is further complicated when dealing with rotations of 180deg or 270deg, rendering the default transform-origin
of 40px 40px
ineffective. Recalculating the transform-origin for each element rotation is impractical and something I aim to avoid.