纯css3制作css
纯 CSS3 制作动画的方法
使用 CSS3 制作动画主要通过 @keyframes 规则和 animation 属性实现。以下是具体实现方式:
定义关键帧动画
@keyframes example {
0% { background-color: red; }
50% { background-color: yellow; }
100% { background-color: green; }
}
关键帧通过百分比定义动画阶段,0% 是起始状态,100% 是结束状态。
应用动画到元素
div {
width: 100px;
height: 100px;
animation-name: example;
animation-duration: 4s;
}
animation-name 指定关键帧名称,animation-duration 设置动画时长。
常用动画属性
控制动画播放次数

div {
animation-iteration-count: 3; /* 有限次数 */
animation-iteration-count: infinite; /* 无限循环 */
}
设置动画方向
div {
animation-direction: alternate; /* 往返播放 */
}
延迟动画开始
div {
animation-delay: 2s; /* 延迟2秒 */
}
定义速度曲线

div {
animation-timing-function: ease-in-out; /* 缓入缓出 */
}
可选值:linear、ease、ease-in、ease-out、ease-in-out。
复合动画写法
div {
animation: example 3s ease-in 1s infinite alternate;
}
属性顺序:名称 时长 速度曲线 延迟 次数 方向。
变换动画(Transform)
结合 transform 实现更复杂效果:
@keyframes rotate {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
过渡效果(Transition)
用于属性变化的平滑过渡:
button {
transition: background-color 0.5s ease;
}
button:hover {
background-color: blue;
}
性能优化建议
优先使用 opacity 和 transform 属性,这两个属性不会触发重排,性能开销较小。避免在动画中使用 box-shadow 或 border-radius 等高性能消耗属性。






