過渡(Transition)
過渡把「狀態 A → 狀態 B」做成連續變化,典型觸發是 :hover、:focus、class 切換。它沒有關鍵幀,只有起點與終點。
基本用法
把 transition 寫在休息狀態,不要只寫在 :hover 裡,否則滑鼠移開會瞬間跳回。
.btn {
background: #264de4;
color: white;
transition: background 0.2s ease, transform 0.2s ease;
}
.btn:hover {
background: #1a3bb8;
transform: translateY(-1px);
}
子屬性
| 屬性 | 意義 |
|---|---|
transition-property |
要過渡的屬性,all 方便但可能誤傷 |
transition-duration |
時間,UI 微互動約 150–300ms |
transition-timing-function |
速度曲線 |
transition-delay |
延遲 |
縮寫:property duration easing delay。多組用逗號:
速度曲線
| 值 | 感覺 |
|---|---|
ease |
預設,起迄較慢 |
linear |
進度條、無限旋轉 |
ease-in |
離場 |
ease-out |
進場(介面常用) |
ease-in-out |
較長的移動 |
cubic-bezier(...) |
自訂,可做出一點回彈 |
什麼能過渡
可以平滑的多半是數字、顏色、部分 shadow。下列不能當過渡(會直接跳):
displayfont-family- 多數關鍵字切換(例如
float)
height: auto 也無法直接過渡。摺疊面板可用 grid-template-rows: 0fr → 1fr 等技巧,或交給 JS。
只過渡合成友善屬性(transform、opacity)較不易造成版面抖動。
總結
- 過渡寫在預設規則,狀態規則只寫終值。
- 明確列出 property,少用
all。 - 尊重
prefers-reduced-motion(見 媒體查詢)。