css制作简单动画
CSS 制作简单动画的方法
使用 transition 实现过渡动画
通过 transition 属性可以平滑地改变元素的样式。定义需要过渡的属性和持续时间。
.box {
width: 100px;
height: 100px;
background: blue;
transition: width 1s, background 0.5s;
}
.box:hover {
width: 200px;
background: red;
}
使用 @keyframes 创建关键帧动画
通过 @keyframes 定义动画的关键帧,再通过 animation 属性应用动画。
@keyframes slide {
0% {
transform: translateX(0);
}
100% {
transform: translateX(200px);
}
}
.slider {
width: 100px;
height: 100px;
background: green;
animation: slide 2s infinite alternate;
}
使用 transform 实现变形动画
transform 属性可以对元素进行旋转、缩放、移动等操作,结合动画效果更佳。
.rotate {
width: 100px;
height: 100px;
background: yellow;
transition: transform 1s;
}
.rotate:hover {
transform: rotate(45deg) scale(1.2);
}
使用 animation 控制动画播放
通过 animation 的多个子属性可以控制动画的播放方式,如延迟、循环次数等。
.pulse {
width: 100px;
height: 100px;
background: purple;
animation: pulse 1.5s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.1);
}
}
结合伪类触发动画
利用 :hover、:active 等伪类触发动画效果。

.button {
padding: 10px 20px;
background: orange;
transition: all 0.3s;
}
.button:hover {
background: darkorange;
transform: translateY(-3px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
注意事项
- 尽量使用
transform和opacity属性制作动画,性能更高。 - 避免频繁触发重排和重绘的属性(如
width、margin)。 - 使用
will-change提示浏览器优化动画元素。






