CSS 过渡效果
CSS 过渡效果 · 难度:进阶 · +15XP
CSS 过渡效果
CSS transition 允许你在指定的时间内平滑地改变 CSS 属性值。与 animation 不同,transition 需要触发条件(如 :hover、:focus 或 class 变化),且只能在两个状态之间过渡。
transition 属性
| 子属性 | 说明 | 示例 |
|---|---|---|
| transition-property | 要过渡的 CSS 属性 | width, opacity, all |
| transition-duration | 过渡持续时间 | 0.3s, 500ms |
| transition-timing-function | 速度曲线 | ease, linear, ease-in-out |
| transition-delay | 开始前延迟 | 0s, 200ms |
基本用法
/* 按钮 hover 过渡 */
.btn {
background-color: #3498db;
color: white;
padding: 10px 20px;
border: none;
transition: background-color 0.3s ease;
}
.btn:hover {
background-color: #2980b9;
}
/* 链接下划线过渡 */
a {
color: #333;
text-decoration: none;
border-bottom: 2px solid transparent;
transition: border-color 0.3s, color 0.3s;
}
a:hover {
color: #3498db;
border-color: #3498db;
}
过渡多个属性
可以用逗号分隔多个过渡,或使用 all 过渡所有可动画属性:
.card {
background: white;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
transform: translateY(0);
transition: box-shadow 0.3s ease, transform 0.3s ease;
}
.card:hover {
box-shadow: 0 8px 25px rgba(0,0,0,0.2);
transform: translateY(-4px); /* 浮起效果 */
}
/* 使用 all 过渡所有变化 */
.element {
transition: all 0.3s ease;
}
transition-timing-function 详解
| 函数名 | 贝塞尔曲线 | 效果描述 |
|---|---|---|
| ease | cubic-bezier(0.25,0.1,0.25,1) | 慢速开始,快速中间,慢速结束(默认) |
| linear | cubic-bezier(0,0,1,1) | 匀速过渡 |
| ease-in | cubic-bezier(0.42,0,1,1) | 慢速开始,加速结束 |
| ease-out | cubic-bezier(0,0,0.58,1) | 快速开始,减速结束 |
| ease-in-out | cubic-bezier(0.42,0,0.58,1) | 慢速开始和结束 |
过渡简写
/* 顺序: property duration timing-function delay */
transition: width 0.5s ease-in-out 0.2s;
/* 常用简写 */
transition: background-color 0.3s ease;
transition: all 0.3s ease;
transition: transform 0.5s cubic-bezier(0.68, -0.55, 0.27, 1.55); /* 弹性效果 */
可过渡的属性
并非所有属性都可以过渡。以下是常见的可过渡属性:color, background-color, width, height, transform, opacity, margin, padding, border, box-shadow, font-size, letter-spacing 等。
???? 练习
- 创建一个按钮,hover 时背景色和阴影同时平滑变化
- 制作一个卡片,hover 时向上浮动 4px 并增强阴影
- 使用 cubic-bezier 自定义一个弹性过渡曲线
- 给导航链接添加下划线从左滑入的过渡效果
- 对比 ease、ease-in、ease-out 和 linear 在同一元素上的视觉差异