I am trying to rotate a square div about its central axis.
Here is the div:
<div id='my_square' class='square'></div>
CSS:
.square {
width: 200px;
height: 200px;
border: 2px solid white;
position: absolute;
background: #227093;
animation: rotate_x_180 2s;
}
.center {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
@keyframes rotate_x_180{
0% {transform: rotate(180deg);}
100% {transform: rotate(0deg);}
}
I am centering the div using javascript (since the positioning needs to be programmatic):
document.getElementById("my_square").classList.add("center")
This is the result:
Notice the shifting that occurs in position.
Is there a way to maintain the position so that the rotation only occurs about the central axis, with no shifting in position?
Here is the Fiddle
As per @Fabrizio's comment, it does indeed appear that the animation if overriding the negative translation that was applied by JS. I tried to reset this at the end of the animation:
@keyframes rotate_x_180 {
0% {transform: rotate(180deg)}
100% {transform: rotate(0deg) transform: translate(-50%, -50%)}
}
...but the div does not maintain the center position.
The problem lies in the fact that the transforms in the keyframes are overriding the transform which translates the element back to the center.
You can have several settings in the tranform's value, but there can be only one tranform - any subsequent one will completely remove the first one.
Also note that it is important what order the transform settings are done in. In this snippet the square is positioned first with the translate and then rotated about its central point.
document.getElementById("my_square").classList.add("center");
.square {
width: 200px;
height: 200px;
border: 2px solid white;
position: absolute;
background: #227093;
animation: rotate_x_180 2s;
}
.center {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
@keyframes rotate_x_180 {
0% {
transform: translate(-50%, -50%) rotate(180deg);
}
100% {
transform: translate(-50%, -50%) rotate(0deg)
}
}
<div id='my_square' class='square'></div>