@keyframes 是 CSS 動畫的核心,定義動畫關鍵幀樣式。本文詳細說明語法結構、from/to 與百分比寫法、多關鍵幀排序、配合 animation 屬性使用的完整範例。
@keyframes 動畫名稱 {
from { /* 0% */ 屬性: 值; }
百分比 { 屬性: 值; }
to { /* 100% */ 屬性: 值; }
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-100px); animation-timing-function: ease-out; }
100% { transform: translateY(0); animation-timing-function: ease-in; }
}
@keyframes complex {
0% { opacity: 0; transform: scale(0.5) rotate(-180deg); background: red; }
50% { opacity: 1; transform: scale(1.2) rotate(0); background: yellow; }
100% { opacity: 1; transform: scale(1) rotate(0); background: green; }
}
from 必為 0%,to 必為 100%,不可寫成其他值。.box {
animation: fadeIn 1s ease-out 0s 1 normal forwards running;
}
/* 縮寫順序:name duration timing-function delay iteration-count direction fill-mode play-state */
animation-name:對應 @keyframes 名稱animation-duration:持續時間(秒/毫秒)animation-timing-function:ease、linear、ease-in、ease-out、cubic-bezier()、steps()animation-delay:延遲啟動animation-iteration-count:次數或 infiniteanimation-direction:normal、reverse、alternate、alternate-reverseanimation-fill-mode:none、forwards(保留末幀)、backwards、bothanimation-play-state:running、paused@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(255,0,0,0.7); }
70% { box-shadow: 0 0 0 20px rgba(255,0,0,0); }
100% { box-shadow: 0 0 0 0 rgba(255,0,0,0); }
}
.pulse-btn {
width: 60px; height: 60px; border-radius: 50%;
background: #ff3b30;
animation: pulse 2s infinite;
}
will-change: transform, opacity;),但勿濫用。width/height/margin/padding/top/left 會觸發重排。@keyframes 讓 CSS 擁有時間軸控制能力。熟練掌握百分比關鍵幀、多屬性協同、timing-function 節奏控制,配合 animation 縮寫與效能原則,即可創作流暢、高效能的網頁動畫。