css3前端动画制作
CSS3 前端动画制作方法
使用 transition 制作过渡动画
transition 用于在元素状态变化时添加平滑过渡效果。可以定义过渡的属性、持续时间、延迟时间和速度曲线。
.box {
width: 100px;
height: 100px;
background: red;
transition: width 2s, height 2s, background 2s;
}
.box:hover {
width: 200px;
height: 200px;
background: blue;
}
使用 @keyframes 创建关键帧动画
@keyframes 允许定义动画的中间状态,通过百分比或 from/to 语法控制动画序列。

@keyframes slide {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
.element {
animation: slide 2s ease-in-out infinite alternate;
}
使用 transform 实现变形动画
transform 提供旋转、缩放、倾斜或平移元素的功能,常与动画结合使用。
.spin {
transform: rotate(0deg);
animation: spin 2s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
使用 animation 属性控制动画
animation 是复合属性,包含以下子属性:

animation-name:指定@keyframes名称。animation-duration:动画持续时间。animation-timing-function:速度曲线(如ease、linear)。animation-delay:动画延迟时间。animation-iteration-count:播放次数(如infinite)。animation-direction:播放方向(如alternate)。
.bounce {
animation: bounce 1s ease-in-out 0.5s 3 alternate;
}
使用硬件加速优化性能
通过 transform 和 opacity 触发 GPU 加速,提升动画流畅度。
.optimized {
transform: translateZ(0);
will-change: transform;
}
响应式动画设计
结合媒体查询(@media)适配不同设备尺寸。
@media (max-width: 600px) {
.mobile-animation {
animation: slide 1s ease;
}
}
示例:按钮悬停效果
.button {
padding: 10px 20px;
background: #3498db;
color: white;
border: none;
transition: all 0.3s;
}
.button:hover {
background: #2980b9;
transform: scale(1.05);
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
注意事项
- 避免过度使用动画,以免影响用户体验。
- 使用
will-change提前告知浏览器可能的变化。 - 测试动画在不同浏览器和设备的兼容性。
- 优先使用
transform和opacity实现动画,性能更高。





