CSS 动画有几种方式?
1. CSS 动画的概念
CSS 动画(CSS Animations)是为层叠样式表建议的允许可扩展标记语言(XML)元素使用 CSS 的动画的模块,即指元素从一种样式逐渐过渡为另一种样式的过程。
常见的动画效果有很多,如平移、旋转、缩放等等,复杂动画则是多个简单动画的组合。
CSS 实现动画的方式主要有以下几种:transition、transform、animation。
2. transition(过渡)
transition: <property> <duration> <timing-function> <delay>。
注意:并不是所有的属性都能使用过渡,如 display: none → display: block 这种离散属性无法过渡。
3. transform(转换动画)
一般配合 transition 使用,不支持 inline 元素,使用前需要把它变成 block 或 inline-block。
4. animation(自定义动画)
CSS 动画需要定义一些关键的帧,通过 @keyframes 来定义关键帧:
@keyframes name {
from {
transform: rotate(0deg);
}
to {
transform: rotate(180deg);
}
}
或使用百分比:
@keyframes name {
0% {
transform: rotate(0deg);
}
50% {
transform: rotate(180deg);
}
100% {
transform: rotate(360deg);
}
}
使用:
.box {
animation: name 2s ease infinite;
}
补充:
animation简写顺序为name duration timing-function delay iteration-count direction fill-mode play-state。- 性能上
transform/opacity动画可触发 GPU 合成,是最推荐的动画属性;width/height/top/left会触发回流,应避免。- 想让动画在结束后保留终态,可以设置
animation-fill-mode: forwards。



