Contents

[CSS3]transition的轉場效果

CSS3 的 transition 屬性讓元素在狀態改變時(例如 :hover:focus)能夠平滑地過渡,而不是瞬間切換。

語法

1
transition: property duration timing-function delay;

四個參數說明

1. property(過渡的 CSS 屬性)

指定要套用過渡效果的 CSS 屬性名稱,或使用 all 套用到所有可動畫屬性:

1
2
3
transition: width 0.3s ease;       /* 只對 width 套用 */
transition: all 0.3s ease;         /* 對所有屬性套用 */
transition: opacity 0.5s, transform 0.3s;  /* 多個屬性 */

2. duration(持續時間)

動畫執行的時間長度,單位為秒(s)或毫秒(ms):

1
2
transition: opacity 0.5s;    /* 0.5 秒 */
transition: opacity 500ms;   /* 500 毫秒(同上) */

3. timing-function(緩動函式)

控制動畫在時間軸上的速度變化:

說明
ease 預設值,慢→快→慢
linear 等速,全程速度一致
ease-in 慢開始,逐漸加速
ease-out 快開始,逐漸減速
ease-in-out 慢→快→慢(比 ease 更對稱)
cubic-bezier(x1,y1,x2,y2) 自訂貝茲曲線
1
2
/* 自訂緩動曲線 */
transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);

4. delay(延遲時間)

等待多久後才開始執行動畫:

1
transition: opacity 0.3s ease 0.5s;  /* 延遲 0.5 秒後開始 */

實際範例

按鈕 Hover 效果

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
.btn {
  background-color: #3498db;
  color: white;
  padding: 10px 20px;
  border: none;
  transition: background-color 0.3s ease, transform 0.2s ease;
}

.btn:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
}

卡片展開效果

1
2
3
4
5
6
7
8
9
.card {
  height: 100px;
  overflow: hidden;
  transition: height 0.4s ease-in-out;
}

.card:hover {
  height: 300px;
}

淡入淡出效果

1
2
3
4
5
6
7
8
.tooltip {
  opacity: 0;
  transition: opacity 0.25s ease;
}

.tooltip.visible {
  opacity: 1;
}

注意事項

  • 並非所有 CSS 屬性都可以過渡,例如 display: none 無法過渡,需改用 opacity + visibility
  • transition 定義在初始狀態的元素上,不是在 :hover 上(否則移出時不會有動畫)。

參考資料