简体   繁体   English

如何使用CSS将动画应用于垂直居中的元素

[英]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. 我想将CSS动画应用于另一个div中的一个div。 The problem seems to be that I am applying multiple transforms to the div. 问题似乎是我正在对div应用多个转换。 In order to center the inner div, I am using the following: 为了使内部div居中,我使用以下方法:

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

I then add the following class to the div on click: 然后,我将以下类添加到div上:

.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. 似乎我已经使用了一个transform来使div居中的事实使得它不能正确播放动画。 If I remove the transform: translate(-50%, -50%); 如果我删除transform: translate(-50%, -50%); line from the CSS, the animation works correctly, but the div is not centered. 在CSS中排成一行,动画即可正常工作,但div不在居中。

Here is a jsfiddle I made to demonstrate the issue. 这是我制作的jsfiddle来演示此问题。

Thanks for your help! 谢谢你的帮助!

The issue is because the translate is lost on animation .change it by adding both translate and rotate on animation 问题是因为translateanimation上丢失了。通过在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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM