transition 讓 CSS 屬性值變化時產生平滑動畫,語法四要素:property、duration、timing-function、delay。
.element {
-webkit-transition: property duration timing-function delay;
-moz-transition: property duration timing-function delay;
-o-transition: property duration timing-function delay;
transition: property duration timing-function delay;
}
| 屬性 | 值類型 |
|---|---|
| color | 顏色 |
| background-color | 顏色 |
| opacity | 數值 0~1 |
| width / height | 長度、百分比 |
| margin / padding | 長度、百分比 |
| transform | 變換函數 |
| font-size / line-height | 長度、百分比、數值 |
| letter-spacing / word-spacing | 長度 |
| text-indent | 長度、百分比 |
| border-width / outline-width | 長度 |
| z-index | 整數 |
| visibility | 可見性關鍵字 |
不可動畫:display、position、float、background-image(漸變視為圖片)等離散值屬性。
| 關鍵字 | 曲線特性 | 適用場景 |
|---|---|---|
| linear | 勻速 | 機械感、無限循環 |
| ease | 慢→快→慢(預設) | 大多數 UI 互動 |
| ease-in | 加速(漸入) | 元素進場 |
| ease-out | 減速(淡出) | 元素離場、彈窗關閉 |
| ease-in-out | 加速後減速 | 來回切換 |
| cubic-bezier(x1,y1,x2,y2) | 自訂貝塞爾曲線 | 品牌專屬動感、彈跳、彈性 |
.btn {
background: #3498db;
transition: background 0.3s ease, transform 0.1s ease-out;
}
.btn:hover { background: #2980b9; }
.btn:active { transform: scale(0.98); }
/* 延遲登場 */
.card:nth-child(1) { transition-delay: 0ms; }
.card:nth-child(2) { transition-delay: 100ms; }
.card:nth-child(3) { transition-delay: 200ms; }
transform、opacity(合成器執行緒,不觸發重排/重繪)。width/height/margin/top/left 等佈局屬性。will-change: transform, opacity; 提前提示瀏覽器(慎用,記得移除)。