⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

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 详解

函数名贝塞尔曲线效果描述
easecubic-bezier(0.25,0.1,0.25,1)慢速开始,快速中间,慢速结束(默认)
linearcubic-bezier(0,0,1,1)匀速过渡
ease-incubic-bezier(0.42,0,1,1)慢速开始,加速结束
ease-outcubic-bezier(0,0,0.58,1)快速开始,减速结束
ease-in-outcubic-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 等。

???? 练习

  1. 创建一个按钮,hover 时背景色和阴影同时平滑变化
  2. 制作一个卡片,hover 时向上浮动 4px 并增强阴影
  3. 使用 cubic-bezier 自定义一个弹性过渡曲线
  4. 给导航链接添加下划线从左滑入的过渡效果
  5. 对比 ease、ease-in、ease-out 和 linear 在同一元素上的视觉差异

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 122 篇
0 完成
🔥 0