使用css中的动画和vh单位居中一个div?

时间:2014-06-29 10:55:14

标签: html css css3 css-animations viewport-units

所以我有一个div,让我们说width: 7vh; height: 7vh; background: black;并且它在另一个div background: orange; height: 7vh; width: 100%;内。我有一个动画片,它应该会取消它。目前我在内部div上使用left: 50%,但显然它接近于居中,但实际上并非如此。 margin: 0 auto;margin-left: auto; margin-right: auto;没有动画效果。那我该怎么办?用JS计算距离是我唯一的解决方案吗?

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

这个例子并不是以它为中心,只是通过使用left: 50%;

来接近这样做

1 个答案:

答案 0 :(得分:1)

您可以在动画开头使用margin-left:-3.5vh;将正方形居中,并在关键帧动画中将其设置为0:

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