Search code examples
htmlcsscss-animationsviewport-units

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; and it's inside another div, 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; 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%;


Solution

  • 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);}
    }