CSS過渡是在CSS中創建動畫的最簡單的方法。在過渡中,您更改屬性的值,並告訴CSS根據某些參數慢慢將其變化到最終狀態。
CSS過渡介紹
CSS過渡是在CSS中創建動畫的最簡單的方法。
在過渡中,您更改屬性的值,並告訴CSS根據某些參數慢慢將其變化到最終狀態。
CSS過渡由以下屬性定義:
| 屬性 | 描述 |
|---|---|
transition-property |
應過渡的CSS屬性 |
transition-duration |
過渡的持續時間 |
transition-timing-function |
動畫使用的時間函數(常見值:linear,ease)。默認值:ease |
transition-delay |
開始動畫之前的可選秒數 |
transition屬性是一個方便的簡寫:
.container {
transition: property duration timing-function delay;
}
CSS過渡的示例
以下代碼實現了一個CSS過渡:
.one,
.three {
background: rgba(142, 92, 205, 0.75);
transition: background 1s ease-in;
}
.two,
.four {
background: rgba(236, 252, 100, 0.75);
}
.circle:hover {
background: rgba(142, 92, 205, 0.25); /* 淺色 */
}
在懸停在.one和.three元素上時,即紫色圓圈,有一個過渡動畫,平滑地改變背景顏色,而黃色圓圈則不會,因為它們沒有定義transition屬性。
過渡的時間函數值
transition-timing-function允許指定過渡的加速曲線。
這裡有一些簡單的值可以使用:
| 值 |
|---|
| linear |
| ease |
| ease-in |
| ease-out |
| ease-in-out |
這個Glitch展示了這些值在實踐中的工作方式。
您可以使用cubic bezier curves創建完全定制的時間函數。這比較高級,但基本上這些函數中的任何一個都使用bezier曲線構建。我們有方便的名稱,因為它們是常見的值。
瀏覽器DevTools中的CSS過渡
瀏覽器DevTools提供了一個很好的可視化過渡的方式。
這是Chrome:
這是Firefox:
您可以通過這些面板實時編輯過渡並在頁面上直接進行實驗,而無需重新加載代碼。
可以使用CSS過渡動畫的屬性
非常多!但不是所有CSS屬性。
以下是完整列表:
| 屬性 |
|---|
| background |
| background-color |
| background-position |
| background-size |
| border |
| border-color |
| border-width |
| border-bottom |
| border-bottom-color |
| border-bottom-left-radius |
| border-bottom-right-radius |
| border-bottom-width |
| border-left |
| border-left-color |
| border-left-width |
| border-radius |
| border-right |
| border-right-color |
| border-right-width |
| border-spacing |
| border-top |
| border-top-color |
| border-top-left-radius |
| border-top-right-radius |
| border-top-width |
| bottom |
| box-shadow |
| caret-color |
| clip |
| color |
| column-count |
| column-gap |
| column-rule |
| column-rule-color |
| column-rule-width |
| column-width |
| columns |
| content |
| filter |
| flex |
| flex-basis |
| flex-grow |
| flex-shrink |
| font |
| font-size |
| font-size-adjust |
| font-stretch |
| font-weight |
| grid-area |
| grid-auto-columns |
| grid-auto-flow |
| grid-auto-rows |
| grid-column-end |
| grid-column-gap |
| grid-column-start |
| grid-column |
| grid-gap |
| grid-row-end |
| grid-row-gap |
| grid-row-start |
| grid-row |
| grid-template-areas |
| grid-template-columns |
| grid-template-rows |
| grid-template |
| grid |
| height |
| left |
| letter-spacing |
| line-height |
| margin |
| margin-bottom |
| margin-left |
| margin-right |
| margin-top |
| max-height |
| max-width |
| min-height |
| min-width |
| opacity |
| order |
| outline |
| outline-color |
| outline-offset |
| outline-width |
| padding |
| padding-bottom |
| padding-left |
| padding-right |
| padding-top |
| perspective |
| perspective-origin |
| quotes |
| right |
| tab-size |
| text-decoration |
| text-decoration-color |
| text-indent |
| text-shadow |
| top |
| transform. |
| vertical-align |
| visibility |
| width |
| word-spacing |
| z-index |