网站
引入
CSS 过渡用于让样式变化更平滑。
没有过渡时,元素状态会瞬间改变;加上过渡后,变化会有一个过程。
正文
定义
定义
transition用于设置元素从一种样式变化到另一种样式时的过渡效果。
过渡通常和 :hover、:focus、:active 等状态一起使用。
语法
选择器 {
transition: 属性 持续时间 速度曲线 延迟时间;
}例如:
.box {
background-color: blue;
transition: background-color 0.3s ease;
}
.box:hover {
background-color: red;
}鼠标移到 .box 上时,背景色会在 0.3s 内从蓝色变成红色。
常见属性
| 属性 | 作用 |
|---|---|
transition-property | 指定要过渡的属性 |
transition-duration | 指定过渡持续时间 |
transition-timing-function | 指定过渡速度曲线 |
transition-delay | 指定过渡延迟时间 |
transition | 过渡简写属性 |
单个属性过渡
.btn {
background-color: #2563eb;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #1d4ed8;
}这个例子只让 background-color 产生过渡。
多个属性过渡
多个属性可以用逗号 , 分隔。
.card {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
}鼠标移上去时,卡片会轻微上浮,阴影也会变明显。
transition: all
transition: all 0.3s ease; 表示所有可过渡属性都参与过渡。
.box {
transition: all 0.3s ease;
}这种写法方便,但不够精确。实际项目里更建议写清楚要过渡的属性。
.box {
transition: transform 0.3s ease, opacity 0.3s ease;
}例子
按钮悬停效果
<button class="btn">提交</button>.btn {
padding: 8px 16px;
border: none;
border-radius: 8px;
background-color: #2563eb;
color: white;
transition: background-color 0.2s ease, transform 0.2s ease;
}
.btn:hover {
background-color: #1d4ed8;
transform: translateY(-2px);
}鼠标移到按钮上时,按钮颜色变深,并轻微上移。
输入框聚焦效果
<input class="input" placeholder="请输入用户名">.input {
padding: 8px 12px;
border: 1px solid #d1d5db;
border-radius: 6px;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
.input:focus {
border-color: #2563eb;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2);
outline: none;
}输入框获得焦点时,边框和外圈阴影会平滑变化。
特点
transition适合做状态变化效果- 常和
:hover、:focus、:active一起使用 - 必须有样式变化,过渡才会发生
- 过渡不是一直播放,而是在状态变化时触发
- 建议优先过渡
opacity、transform、color、background-color - 不建议随便使用
transition: all;
理解
过渡可以理解为“不要突然变,慢慢变”。
它最适合处理按钮、卡片、链接、输入框这些交互状态,让页面看起来更自然。
如果是简单的状态变化,用 transition 就够了;如果是完整的连续动作,再考虑 CSS 动画。
引出
理解过渡之后,可以继续学习 CSS 2D 和 3D 转换,因为 transition 经常和 transform 一起使用。