Comportamiento extraño al girar un elemento al pasar el mouse
Dados estos dos ejemplos.
Usando Hoverdiv {
position: absolute;
width: 150px;
height: 40px;
background: orange;
left: 50%;
top: var(--top);
transition: transform 2s;
transform: translateX(-50%);
text-align: center;
line-height: 40px;
font-size: 1.2em;
}
div:hover {
transform: translateX(-50%) rotate(var(--deg));
}
div:nth-child(1) {
--deg: 180deg;
--top: 20%;
}
div:nth-child(2) {
--deg: -180deg;
--top: 40%;
}
div:nth-child(3) {
--deg: 360deg;
--top: 60%;
}
<div>180deg</div>
<div>-180deg</div>
<div>360deg</div>
Utilizando Animacióndiv {
position: absolute;
width: 150px;
height: 40px;
background: orange;
left: 50%;
top: var(--top);
transform: translateX(-50%);
text-align: center;
line-height: 40px;
font-size: 1.2em;
animation: rotate 2s linear 2s;
}
@keyframes rotate {
to {
transform: translateX(-50%) rotate(var(--deg));
}
}
div:nth-child(1) {
--deg: 180deg;
--top: 20%;
}
div:nth-child(2) {
--deg: -180deg;
--top: 40%;
}
div:nth-child(3) {
--deg: 360deg;
--top: 60%;
}
<div>180deg</div>
<div>-180deg</div>
<div>360deg</div>
Como puedes verrotate(180deg)
yrotate(-180deg)
actúa igual yrotate(360deg)
no se mueve en absoluto.
l problema es que si desea que se mueva gradualmente, actúa normalment
div {
position: absolute;
width: 150px;
height: 40px;
background: orange;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
text-align: center;
line-height: 40px;
font-size: 1.2em;
}
div:hover {
animation: rotate 2s linear;
}
@keyframes rotate {
0% {
transform: translate(-50%, -50%) rotate(0deg);
}
25% {
transform: translate(-50%, -50%) rotate(45deg);
}
50% {
transform: translate(-50%, -50%) rotate(90deg);
}
75% {
transform: translate(-50%, -50%) rotate(135deg);
}
100% {
transform: translate(-50%, -50%) rotate(180deg);
}
}
<div></div>
La solución que encontré es reemplazartranslate(-50%, -50%)
conmargins
que no es consistente
div {
position: absolute;
width: 150px;
height: 40px;
background: orange;
left: 50%;
top: var(--top);
transition: transform 2s;
/* Minus half the width, hard coded not a good idea*/
margin: 0 0 0 -75px;
text-align: center;
line-height: 40px;
font-size: 1.2em;
}
div:hover {
transform: rotate(var(--deg));
}
div:nth-child(1) {
--deg: 180deg;
--top: 20%;
}
div:nth-child(2) {
--deg: -180deg;
--top: 40%;
}
div:nth-child(3) {
--deg: 360deg;
--top: 60%;
}
<div>180deg</div>
<div>-180deg</div>
<div>360deg</div>
Entonces, la pregunta principal es ¿Por qué está teniendo lugar ese comportamiento extraño?
EDIT: No busco solo una respuesta rápida (como puede ver, hay dos disponibles) sino también una explicación:)