CSS 动画是一种使网页元素动态变化的强大工具。通过 CSS 动画,我们可以让网页更加生动有趣。

CSS 动画基础

  1. 关键帧动画 (Keyframe Animation): 通过定义一系列关键帧,可以控制动画的每一帧的状态。例如:

    @keyframes example {
      0% { background-color: red; width: 100px; height: 100px; }
      50% { background-color: yellow; width: 200px; height: 200px; }
      100% { background-color: green; width: 100px; height: 100px; }
    }
    
  2. 动画属性: 使用 animation 属性可以控制动画的执行。例如:

    div {
      animation-name: example;
      animation-duration: 4s;
      animation-timing-function: linear;
      animation-iteration-count: infinite;
      animation-direction: alternate;
      animation-fill-mode: forwards;
    }
    

实例

以下是一个简单的 CSS 动画示例,演示了如何让一个 div 元素在页面中左右移动:

<div id="moving-div">我是一个移动的 div</div>

<style>
  #moving-div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    animation: move-left-right 4s infinite;
  }

  @keyframes move-left-right {
    0%, 100% { left: 0; }
    50% { left: 100%; }
  }
</style>

更多关于 CSS 动画的介绍,可以参考 CSS 动画教程

CSS 动画示例