简体   繁体   中英

CSS rotate animation translates the element

I'm having trouble (again) understanding CSS animations- specifically this rotate animation. When you hover over the image it should start to rotate back-and-forth. It does this, but only after shifting over to the bottom left. I've been looking for similar questions but haven't found an answer as to why this happens or how to prevent it.

 img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } img:hover { animation-name: freakout; animation-duration: .5s; animation-iteration-count: infinite; } @keyframes freakout { 0%, 100% { -ms-transform: rotate(0deg); /* IE 9 */ -webkit-transform: rotate(0deg); /* Chrome, Safari, Opera */ transform: rotate(0deg); } 50% { -ms-transform: rotate(7deg); /* IE 9 */ -webkit-transform: rotate(7deg); /* Chrome, Safari, Opera */ transform: rotate(7deg); } }
 <img src="http://www.swimwithamanatee.biz/normal_ian-symbol-trichechus-spp22_left.png" />

Reason behind this is that in img tag Transform property uses Translate function so as to align the image to center but the moment you hover over the image the Transform property changes to Rotate property resulting in shifting of position while hovering over the image.I changed the code ,This will work.

 img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } img:hover { animation-name: freakout; animation-duration: .5s; animation-iteration-count: infinite; } @keyframes freakout { 0%, 100% { -ms-transform: rotate(0deg)translate(-50%, -50%); /* IE 9 */ -webkit-transform: rotate(0deg)translate(-50%, -50%); /* Chrome, Safari, Opera */ transform: rotate(0deg)translate(-50%, -50%); } 50% { -ms-transform: rotate(7deg)translate(-50%, -50%); /* IE 9 */ -webkit-transform: rotate(7deg)translate(-50%, -50%); /* Chrome, Safari, Opera */ transform: rotate(7deg)translate(-50%, -50%); } }
 <img src="http://www.swimwithamanatee.biz/normal_ian-symbol-trichechus-spp22_left.png" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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