CSS - @keyframes规则



CSS @keyframes 规则用于通过指定动画中帧或步骤的序列来定义动画。该规则通过定义关键帧来指定动画序列中的中间步骤。每个关键帧描述动画在特定时间点(从开始(0%)到结束(100%),以及我们选择定义的任何中间点)的特定状态。

语法

@keyframes animation-name {keyframes-selector {css-styles;}}

属性值

描述
animation-name 它指定包含动画代码的关键帧的名称。必需。
关键帧选择器 它指定动画持续时间的百分比。有效值包括:0% 到 100% / from (0%) - to(100%)。
css样式 它指定在动画过程中必须发生更改的 CSS 样式属性。

CSS关键帧规则示例

以下示例通过不同的示例解释了@keyframe规则。

使用@Keyframe更改颜色的动画

以下示例演示了颜色变化动画。keyframes名称为colorchange。使用的选择器是从0%到100%,通过25%、50%和75%。发生变化的样式属性是background-color、color和top属性。

示例

<!DOCTYPE html>
<html>
<head>

   <style>
      .container {
         height: 400px;
         width: 100%;
         background-color: lightgray;
      }
      .container >div{
         position: relative;
         height: 60px;
         border: 3px solid gray;
         animation: colorchange 6s infinite;
         text-align: center;
         font-size: 36px;
         font-weight: bold;
      }
      @keyframes colorchange{
         0%   {top: 0px;  background-color: red; color: white;}
         25%  {top: 75px;  background-color: white; color: black;}
         50%  {top: 150px;  background-color: lightblue; color: brown;}
         75%  {top: 225px;  background-color: #457b9d; color: orange;}
         100% {top: 300px;  background-color: darkblue; color: yellow;}
      }

   </style>
</head>
<body>
   <h2>
      CSS @keyframes rule
   </h2>
   <h4>
      Changing color example
   </h4>
   <div class="container">
      <div>
         TutorialsPoint
      </div>
   </div>
</body>
</html>

使用@Keyframes的运动示例

以下示例演示了运动动画。keyframes名称为motion。使用的选择器是从0%到100%,通过50%。发生变化的样式属性是translateX。

示例

<!DOCTYPE html>
<html>

<head>

   <style>
      .container {
         height: 200px;
         width: 100%;
         background-color: lightgray;
         border-bottom: 10px solid orange;
      }

      .container>div {
         position: relative;
         height: 80px;
         width: 80px;
         border-radius: 50%;
         border: 3px solid gray;
         animation: motion 6s infinite;
         top: 117px;
         background-color: black;
      }

      .inner {
         position: relative;
         height: 45px;
         width: 45px;
         border-radius: 50%;
         background-color: lightgray;
         top: 16px;
         left: 17px;
      }

      @keyframes motion {
         0% {
               transform: translateX(0px);
         }
         50% {
               transform: translateX(475px);
         }
         100% {
               transform: translateX(0px);
         }
      }
   </style>
</head>

<body>
   <h2>
      CSS @keyframes rule
   </h2>
   <h4>
      motion example
   </h4>
   <div class="container">
      <div>
         <div class="inner">
         </div>
      </div>
   </div>
</body>

</html>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
@keyframes 43.0 10.0 16.0 9.0 30.0
css_properties_reference.htm
广告