css3制作简单动画
使用 CSS3 制作简单动画
CSS3 提供了多种方式来实现动画效果,主要包括 transition 和 animation 两种方法。以下是具体的实现方式。
使用 transition 实现过渡动画
transition 用于在元素状态变化时添加平滑的过渡效果。例如,当鼠标悬停时改变元素的颜色或大小。
.box {
width: 100px;
height: 100px;
background-color: red;
transition: all 0.3s ease;
}
.box:hover {
background-color: blue;
transform: scale(1.2);
}
transition: all 0.3s ease;表示所有属性变化都会在 0.3 秒内以缓动效果过渡。:hover伪类触发状态变化。
使用 @keyframes 和 animation 实现关键帧动画
@keyframes 定义动画的关键帧,animation 将动画应用到元素上。
@keyframes slide {
0% {
transform: translateX(0);
}
50% {
transform: translateX(100px);
}
100% {
transform: translateX(0);
}
}
.box {
width: 100px;
height: 100px;
background-color: green;
animation: slide 2s infinite;
}
@keyframes slide定义了一个名为slide的动画,从初始位置向右移动 100px 再返回。animation: slide 2s infinite;将动画应用到元素,持续 2 秒并无限循环。
使用 transform 实现变形动画
transform 可以实现旋转、缩放、平移等效果,通常与 transition 或 animation 结合使用。
.box {
width: 100px;
height: 100px;
background-color: yellow;
transition: transform 0.5s ease;
}
.box:hover {
transform: rotate(45deg) scale(1.5);
}
transform: rotate(45deg) scale(1.5);在悬停时旋转 45 度并放大 1.5 倍。
使用 opacity 实现淡入淡出效果
通过改变 opacity 属性可以实现元素的淡入淡出效果。
.box {
width: 100px;
height: 100px;
background-color: purple;
opacity: 0.5;
transition: opacity 0.5s ease;
}
.box:hover {
opacity: 1;
}
opacity: 0.5;设置初始透明度为 50%。transition: opacity 0.5s ease;使透明度变化平滑。
使用 animation-fill-mode 控制动画结束状态
animation-fill-mode 可以定义动画结束后元素的样式。
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.box {
width: 100px;
height: 100px;
background-color: orange;
animation: fadeIn 2s forwards;
}
animation-fill-mode: forwards;使动画结束后保持最后一帧的状态。
通过以上方法,可以轻松实现各种简单的 CSS3 动画效果。






