高度上的CSS动画与cubic-bezier改变位置

时间:2013-10-22 08:03:56

标签: html css css3

我正在尝试使用CSS3,我发现了一件奇怪的事情。当我将CSS动画设置为height属性并使用cubic bezier (0,n,0.5,1),其中n大于0.5时,元素在动画期间向下移动。

这种解释是对的吗?在Firefox和Chrome中似乎是一样的。 Live demo(由于某种原因在Chrome中不起作用)

2 个答案:

答案 0 :(得分:2)

我在Chrome中无法使用,因为您在keframes中使用%而不是px,而父元素没有设置高度。

整体行为是正确的,这是因为你已经使元素内联元素,这使得它们默认情况下与基线对齐,而行为最明显的动画速度不同,你会体验到在同步线性运动结束时的相同行为,即它与立方贝塞尔缓和并不真正相关。

您可以通过将vertical-align更改为top

来解决此问题
.box {
    width: 50px;
    display: inline-block;
    vertical-align: top;
    background: #5f0;
    height: 100px;
    border: 1px solid #000;
}

或浮动元素而不是使它们成为内联元素。

.box {
    width: 50px;
    float: left;
    background: #5f0;
    height: 100px;
    border: 1px solid #000;
}

答案 1 :(得分:1)

演示似乎无法在Chrome中运行问题,因为来自关键帧的的高度为100%,但这意味着100%包含元素(在本例中为<body>),但<body>上没有设置高度。两个解决方案,设置:

body {
    height:100px;
}

@-webkit-keyframes anim {
    from {
        height:100px;
    }
    to {
        height:0;
    }
}

实际的移动元素问题是因为元素是display:inline-block但没有设置vertical-align,因此浏览器使用默认的vertical-align:baseline来对齐要素。由于每个块的cubic-bezier的动画属性不同,因此基线正在移动,因此元素也是如此。

有关基线移动原因的详细信息,请参阅我在 Why does this inline-block element have content that is not vertically aligned 上的回答。

因此,如果每个块上的动画属性相同,则不会出现问题。

对于我的demo,我使用vertical-align:top;are other values取决于您的需求。我还设置animation-fill-mode:forwards以便“在动画结束后(由其animation-iteration-count确定),动画将应用动画结束时的属性值” - {em>来自{{ 3}}

<强> CSS

@keyframes anim {
    from {
        height: 100px;
    }
    to {
        height: 0;
    }
}
@-webkit-keyframes anim {
    from {
        height:100px;
    }
    to {
        height:0;
    }
}
.box {
    width: 50px;
    display: inline-block;
    background: #5f0;
    height: 100px;
    border: 1px solid #000;
    vertical-align:top;
}
.box:first-of-type {
    animation: anim 10s cubic-bezier(0, 1, .5, 1);
    -webkit-animation: anim 10s cubic-bezier(0, 1, .5, 1) forwards;
}
.box:last-of-type {
    animation: anim 10s cubic-bezier(0, .5, .5, 1);
    -webkit-animation: anim 10s cubic-bezier(0, .5, .5, 1) forwards;
}

<强> HTML

<div class=box></div>
<div class=box></div>