Malcolm G
Malcolm G

Reputation: 614

How to apply animation to vertically centered element with CSS

I have a div within another div to which I would like to apply a CSS animation. The problem seems to be that I am applying multiple transforms to the div. In order to center the inner div, I am using the following:

#inner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

I then add the following class to the div on click:

.spin {
    animation: whirl 1s ease-in-out;
}

@keyframes whirl {
    50% {
        transform: rotate(180deg);
    }
    100% {
        transform: rotate(0deg);
    }
}

It seems that the fact that I have already used a transform to center the div makes it so that the animation doesn't work correctly. If I remove the transform: translate(-50%, -50%); line from the CSS, the animation works correctly, but the div is not centered.

Here is a jsfiddle I made to demonstrate the issue.

Thanks for your help!

Upvotes: 0

Views: 90

Answers (1)

XYZ
XYZ

Reputation: 4480

The issue is because the translate is lost on animation.change it by adding both translate and rotate on animation

@keyframes whirl {
  50% {
    transform: translate(-50%, -50%) rotate(180deg);
  }
  100% {
    transform: translate(-50%, -50%) rotate(0deg);
  }
}

function spin() {
  $("#inner").addClass("spin");
}
#main {
  background-color: black;
  position: relative;
  width: 400px;
  height: 400px;
}

#inner {
  background-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100px;
  height: 100px;
  border-radius: 10px;
 transform: translate(-50%, -50%);
}

.spin {
  animation: whirl 1s ease-in-out;
}

@keyframes whirl {
  50% {
    transform: translate(-50%, -50%) rotate(180deg);
  }
  100% {
    transform: translate(-50%, -50%) rotate(0deg);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <div id="inner" onclick="spin()"></div>
</div>

Upvotes: 1

Related Questions