CSS 背景
CSS 伪类 

CSS 动画

在 CSS 中,可以使用关键帧动画(Keyframes Animation)来创建动画效果。CSS动画使得可以在不使用JavaScript的情况下,在网页上添加动态和交互性。


创建关键帧动画(Keyframes Animation)的步骤:

1、定义关键帧(Keyframes):

使用 @keyframes 规则定义动画中的关键帧。关键帧定义了动画在不同时间点的样式变化。

@keyframes slide-in {
    0% {
        transform: translateX(-100%);
    }
    100% {
        transform: translateX(0);
    }
}

在上面的示例中,slide-in 是动画的名称,0% 和 100% 是时间点,transform 属性指定了元素在动画过程中的变换。


2、应用动画

使用 animation 属性将定义好的关键帧动画应用到元素上。

.box {
    width: 100px;
    height: 100px;
    background-color: blue;
    animation: slide-in 1s ease-out forwards;
}

在上面的示例中,.box 是要应用动画的元素选择器,slide-in 是动画名称,1s 是动画持续时间(1秒),ease-out 是动画速度曲线(缓慢结束),forwards 表示动画结束时应用最后一个关键帧的样式。



动画属性详解:

  • animation-name:指定要应用的关键帧动画的名称。

  • animation-duration:指定动画持续时间。

  • animation-timing-function:指定动画的速度曲线,如 linear、ease-in、ease-out 等。

  • animation-delay:指定动画开始前的延迟时间。

  • animation-iteration-count:指定动画的播放次数,可以是具体次数或者 infinite 表示无限循环。

  • animation-direction:指定动画播放的方向,如 normal(默认)、reverse、alternate 等。

  • animation-fill-mode:指定动画在执行前和执行后如何应用样式,如 forwards、backwards、both 等。


示例:

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  width: 100px;
  height: 100px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
}

@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;}
}
</style>
</head>
<body>
<!-- 动画元素 -->
<div></div>
</body>
</html>