CSS动画如何实现宽度变化?

时间:2018-07-17 03:48:35

标签: html css animation css-animations

我想保持盒子的左侧固定,并随时间增加其宽度,以使右侧水平移动。

我写了下面的代码。您可以在下面的链接中尝试动画

https://www.w3schools.com/code/tryit.asp?filename=FTCPP2062CMB

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    -webkit-animation-name: example; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */
    animation-name: example;
    animation-duration: 4s;

}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes example {
    0%   {background-color:red; left:0px; top:0px;}
    25%  {background-color:yellow; left:200px; top:0px;}
    50%  {background-color:blue; left:200px; top:200px;}
    75%  {background-color:green; left:0px; top:200px;}
    100% {background-color:red; left:0px; top:0px;}
}

/* Standard syntax */
@keyframes example {
    0%   {background-color:red; left:0px; top:0px; transform: scale(0.1,1);}
    25%  {background-color:yellow; left:0px; top:0px; scale(0.1,1);}
    50%  {background-color:blue; left:0px; top:0px; scale(0.1,1);}
    75%  {background-color:green; left:0px; top:0px; scale(0.1,1);}
    100% {background-color:red; left:0px; top:0px; scale(0.1,1);}
}
</style>
</head>
<body>

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>

<div></div>

</body>
</html>

但是它使正方形的中心保持固定并移动了两侧。如何保持一侧固定,而仅水平移动另一侧?

2 个答案:

答案 0 :(得分:2)

更新后的示例:https://www.w3schools.com/code/tryit.asp?filename=FTCQ1CT30YQW

div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    0%   {background-color:red; width: 0;}
    25%  {background-color:yellow;}
    50%  {background-color:blue;}
    75%  {background-color:green;}
    100% {background-color:red; width: 100px;}
}

您可以仅设置宽度的动画,而不使用变换比例。

答案 1 :(得分:0)

您可以使用transform-origin实现这一目标(see MDN documentation)。

transform-origin规则允许您指定从中应用CSS转换的参考点(或原点)。

在您的情况下,关键是它的变换原点相对于<div>的左侧,这是通过将transform-origin的第一个坐标设置为{{ 1}},如下所示在动画的两个阶段:

0%