css过渡
CSS 中的过渡动画(Transitions)允许你在元素的属性值变化时实现平滑的动画效果。通过设置过渡属性,可以控制动画的持续时间、延迟、速度函数等。
# 1. 基本语法
.selector {
property: value; /* 初始状态 */
transition: property duration timing-function delay; /* 过渡效果 */
}
1
2
3
4
2
3
4
- property: 要应用过渡的 CSS 属性(如
background-color
,width
,opacity
等)。 - duration: 动画持续的时间(如
0.5s
,表示 0.5 秒)。 - timing-function: 动画的速度曲线(如
ease
,linear
,ease-in
,ease-out
,ease-in-out
)。 - delay: 动画开始前的延迟时间(可选)。
# 2. 示例代码
以下是一个简单的示例,展示了如何使用 CSS 过渡动画。当鼠标悬停在按钮上时,按钮的背景颜色和宽度平滑改变。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Transition Example</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
margin: 0;
}
.button {
padding: 15px 30px;
background-color: #6200ea;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
transition: background-color 0.3s ease, width 0.3s ease; /* 过渡效果 */
width: 200px; /* 初始宽度 */
}
.button:hover {
background-color: #3700b3; /* 鼠标悬停时的颜色 */
width: 250px; /* 鼠标悬停时的宽度 */
}
</style>
</head>
<body>
<button class="button">Hover Me</button>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 3. 代码解析
HTML 部分:
- 一个简单的按钮元素,用于演示过渡效果。
CSS 部分:
.button
类定义了按钮的基本样式和过渡效果。transition: background-color 0.3s ease, width 0.3s ease;
定义了两个过渡属性:- 背景颜色在 0.3 秒内以
ease
曲线平滑过渡。 - 宽度在 0.3 秒内以
ease
曲线平滑过渡。
- 背景颜色在 0.3 秒内以
.button:hover
定义了鼠标悬停时的样式,分别改变背景颜色和宽度。
# 4. 过渡动画的特点
- 易于实现: 只需使用
transition
属性即可为多个 CSS 属性添加动画效果。 - 性能优越: 使用硬件加速的属性(如
transform
和opacity
)可以提高性能。 - 组合使用: 可以与其他 CSS 特性(如
transform
)结合使用,创建更复杂的动画效果。
# 5. 其他示例
- 透明度过渡:
.fade-in {
opacity: 0; /* 初始透明度 */
transition: opacity 1s ease-in; /* 过渡时长和曲线 */
}
.fade-in:hover {
opacity: 1; /* 鼠标悬停时透明度变化 */
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 变换过渡:
.scale {
transform: scale(1); /* 初始缩放 */
transition: transform 0.3s ease; /* 过渡效果 */
}
.scale:hover {
transform: scale(1.2); /* 鼠标悬停时缩放 */
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 6. 总结
CSS 过渡动画为网页元素的状态变化提供了平滑的视觉转变。通过简单地设置 transition
属性,你可以轻松地为你的网页添加动感效果,提升用户体验。
在线编辑 (opens new window)
上次更新: 2025/02/25, 18:30:54