動畫(Animation & Keyframes)
動畫用關鍵幀描述一段時間內的樣式變化,不必等 hover。適合載入、呼吸燈、骨架屏、裝飾性循環。
最小例子
@keyframes fade-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
.toast {
animation: fade-in 0.4s ease-out both;
}
from / to 等於 0% / 100%。中間可加任意百分比:
主要屬性
| 屬性 | 作用 | 常用 |
|---|---|---|
animation-name |
對應 @keyframes |
fade-in |
animation-duration |
一輪多久 | 400ms、2s |
animation-timing-function |
每輪曲線;也可用 steps(4) |
ease-out |
animation-delay |
開始前等待 | 0.1s |
animation-iteration-count |
次數 | 1、infinite |
animation-direction |
normal、reverse、alternate |
來回用 alternate |
animation-fill-mode |
播完/播前要不要停留在關鍵幀 | forwards、both |
animation-play-state |
running / paused |
hover 暫停 |
animation-composition |
多動畫如何合成 | 進階 |
縮寫(名稱與時間順序習慣):
.loader {
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
fill-mode: forwards 讓最後一幀留著,否則元素會跳回動畫前的樣式。進場常用 both(延遲期間也套用第一幀)。
暫停與減少動態
.marquee:hover { animation-play-state: paused; }
@media (prefers-reduced-motion: reduce) {
.marquee { animation: none; }
}
循環動畫請提供暫停方式,避免前庭敏感使用者不適。
多個動畫
逗號分隔:
注意兩個動畫若都改同一個 transform,會互相覆蓋。把位移與旋轉拆到 wrapper 上較單純。
總結
@keyframes定義過程,animation掛到元素。- 進場用
both/forwards;裝飾循環用infinite+ 可暫停。 - 能用過渡解決的 hover,就不要上 keyframes。
對照表見 過渡與動畫比較。