简体   繁体   中英

Center a div with animation and vh units in css?

So I've got a div, let's say width: 7vh; height: 7vh; background: black; width: 7vh; height: 7vh; background: black; and it's inside another div, background: orange; height: 7vh; width: 100%; background: orange; height: 7vh; width: 100%; . I've got an animation, which is supposed to uncenter it. Currently I am using left: 50% on the inner div, but obviously that's close to centering, but not really it. margin: 0 auto; or margin-left: auto; margin-right: auto; margin-left: auto; margin-right: auto; don't animate. So what do I do? Is calculating the distance with JS my only solution?

JsFiddle http://jsfiddle.net/8e7dk/

This example doesn't center it, it only comes close to doing so, by using left: 50%;

You can center the square with margin-left:-3.5vh; at the beginning of the animation and animate it to 0 in your keyframe animation :

DEMO

CSS :

#outer{
    background: orange;
    height: 7vh;
    width: 100%;
}
#logo{
    height: 7vh;
    position: absolute;
    left: 50%;
    margin-left:-3.5vh;
    width: 7vh;
    -webkit-animation: moveLeft 1s forwards ease-in-out;
    -moz-animation: moveLeft 1s forwards ease-in-out;
    -ms-animation: moveLeft 1s forwards ease-in-out;
    -o-animation: moveLeft 1s forwards ease-in-out;
    animation: moveLeft 1s forwards ease-in-out;
    background: black;
}

@-webkit-keyframes moveLeft {
    from {left: 50%;margin-left:-3.5vh;}
    to {left: 0;margin-left:0; -webkit-transform: rotate(360deg);}
}
@-o-keyframes moveLeft {
    from {left: 50%;margin-left:-3.5vh;}
    to {left: 0;margin-left:0; -webkit-transform: rotate(360deg);}
}
@-moz-keyframes moveLeft {
    from {left: 50%;margin-left:-3.5vh;}
    to {left: 0;margin-left:0; -webkit-transform: rotate(360deg);}
}
@keyframes moveLeft {
    from {left: 50%;margin-left:-3.5vh;}
    to {left: 0;margin-left:0; -webkit-transform: rotate(360deg);}
}

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