css制作简易动画
CSS 制作简易动画的方法
使用 transition 实现过渡动画
通过 transition 属性可以平滑地改变元素的样式,适合简单的状态切换效果。例如改变颜色、大小或位置:
.box {
width: 100px;
height: 100px;
background: blue;
transition: background 0.5s ease, transform 0.3s;
}
.box:hover {
background: red;
transform: scale(1.2);
}
使用 @keyframes 创建关键帧动画
通过定义关键帧实现更复杂的动画序列,需配合 animation 属性使用:

@keyframes slide {
0% {
transform: translateX(0);
}
50% {
transform: translateX(100px);
}
100% {
transform: translateX(0);
}
}
.element {
animation: slide 2s infinite;
}
结合 transform 实现动态效果
transform 提供旋转、缩放、移动等变换功能,常与动画配合:

.spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
使用 will-change 优化性能
对复杂动画可启用硬件加速,减少卡顿:
.animated-item {
will-change: transform, opacity;
}
示例:按钮悬停效果
综合运用过渡和变换实现交互反馈:
.button {
padding: 10px 20px;
background: #3498db;
color: white;
transition: all 0.3s;
}
.button:hover {
background: #2980b9;
transform: translateY(-3px);
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
注意事项
- 避免过度使用动画,保持用户体验流畅。
- 使用
prefers-reduced-motion媒体查询为运动敏感用户提供替代方案:
@media (prefers-reduced-motion: reduce) {
.animation {
animation: none;
}
}






