@keyframes slide-in {
0% { transform: translateX(-100%); opacity: 0; }
60% { transform: translateX(10px); opacity: 1; }
100% { transform: translateX(0); }
}
/* 簡寫 from/to 等同 0%/100% */
@keyframes fade {
from { opacity: 0; }
to { opacity: 1; }
}
/* 多組關鍵幀共用名稱 (罕用) */
@keyframes pulse, shake { ... }
.animated {
/* 順序:name duration timing-function delay iteration-count direction fill-mode play-state */
animation: slide-in 0.5s ease-out 0.2s 3 alternate both running;
}
/* 展開長寫 */
.animated {
animation-name: slide-in;
animation-duration: 0.5s;
animation-timing-function: ease-out;
animation-delay: 0.2s;
animation-iteration-count: 3; /* 數值 / infinite */
animation-direction: alternate; /* normal | reverse | alternate | alternate-reverse */
animation-fill-mode: both; /* none | forwards | backwards | both */
animation-play-state: running; /* running | paused */
}
@-webkit-keyframes slide-in { ... }
@-moz-keyframes slide-in { ... }
@-o-keyframes slide-in { ... }
@keyframes slide-in { ... }
.animated {
-webkit-animation: slide-in 0.5s ease-out;
-moz-animation: slide-in 0.5s ease-out;
-o-animation: slide-in 0.5s ease-out;
animation: slide-in 0.5s ease-out;
}
| 值 | 動畫前 | 動畫後 | 場景 |
|---|---|---|---|
none (預設) | 不套用關鍵幀 | 恢復原樣式 | 循環動畫 |
forwards | 不套用 | 保留 100% / 最後關鍵幀 | 進場動畫定格終態 |
backwards | 套用 0% / 第一關鍵幀 (含 delay 期間) | 恢復原樣式 | 延遲進場,防止閃爍 |
both | 套用首幀 | 保留尾幀 | **最常用**,進場+定格 |
normal:每次正向 (0%→100%)。reverse:每次反向 (100%→0%)。alternate:奇數正向、偶數反向 (來回)。alternate-reverse:奇數反向、偶數正向。/* 關鍵字 */
ease | linear | ease-in | ease-out | ease-in-out
/* 三次貝塞爾 */
cubic-bezier(0.4, 0, 0.2, 1) /* Material Design 標準 */
/* 階躍函數 */
steps(4, end) /* 逐幀動畫,如精靈圖播放 */
.modal-overlay {
opacity: 0;
visibility: hidden;
transition: opacity .3s, visibility .3s;
}
.modal-overlay.open {
opacity: 1; visibility: visible;
}
.modal-content {
transform: scale(0.9) translateY(20px);
opacity: 0;
transition: transform .3s cubic-bezier(0.4,0,0.2,1), opacity .3s;
}
.modal-overlay.open .modal-content {
transform: scale(1) translateY(0);
opacity: 1;
}
/* 退場動畫:獨立 keyframes 避免 fill-mode 衝突 */
@keyframes modal-exit {
to { transform: scale(0.9) translateY(20px); opacity: 0; }
}
.modal-overlay.closing .modal-content {
animation: modal-exit .2s ease-in forwards;
}
transform (translate/scale/rotate)、opacity、filter。避免 width/height, top/left, margin, color, background 等觸發 Layout/Paint。.animated { will-change: transform, opacity; } 提前升層,**動畫結束移除** (animationend 事件)。transform 代替多屬性。@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
animation-play-state: paused 暫停檢查中間狀態。@keyframes 名稱衝突:採用 BEM 命名 animation: component__fade-in。掌握 @keyframes 定義關鍵幀、animation 七大子屬性控制播放參數、fill-mode 掌控首尾狀態、timing-function 設計動感曲線、僅動畫 transform/opacity 保證 60fps,即是 CSS 動畫工程化的核心功力。