Skip to content

2025-12-13

/ 7 分鐘閱讀

/ Advanced Web Dev Quiz

CSS 動畫的渲染成本(Layout、Paint、Composite) ​

此文章是 FrontendMaster 上的 Advanced Web Development Quiz 課程筆記

問題 ​

When animating the following properties, which have the correctly listed rendering costs?
Select all the correct answers.

[1] width: Layout > Paint > Composite
[2] opacity: Paint > Composite
[3] background-image: Composite
[4] left: Layout > Paint > Composite
[5] transform: Paint > Composite

瀏覽器渲染流程 ​

本題在考的是在使用 CSS 做動畫效果時,不同的 CSS 屬性會怎麼觸發瀏覽器渲染。

完整的渲染流程是 Layout > Paint > Composite,若要提升渲染的效率,需要盡量使用觸發越後期的渲染階段的屬性越好。

以下內容是以常見的瀏覽器行為作為範例,實際情況可能會有其他因素 (未分層、搭配特效、子像素繪制等) 造成不同的結果

只會觸發 Composite (效能最佳) ​

只改變視覺效果

  • transform
  • opacity

觸發 Paint + Composite ​

改顏色、背景

  • background-image
  • background-color
  • color
  • border-radius
  • filter
  • box-shadow

觸發 Layout + Paint + Composite (效能最差) ​

改位置、大小

  • 改變元素的尺寸
    • width, height
    • padding, border
  • 重新定位元素位置
    • position, left, right, top, bottom
    • margin
  • 改變元素的排版
    • align-content, align-items, flex, display, text-align

以上未列舉全部屬性,在不同的瀏覽器中也可能有不同的情況,詳情可以透過此網站: https://css-triggers.com/ 查詢 CSS 屬性會觸發的渲染階段

效能優化原則 ​

  1. 動畫優先使用 transform、opacity
  2. 避免在動畫中使用會觸發 Layout 的屬性
  3. 謹慎使用 will-change 會強制建立新的 Layer,佔用記憶體 (後面的文章應該會特別說明這個屬性)

答案 ​

[1] width: Layout > Paint > Composite
[4] left: Layout > Paint > Composite

參考 ​

最後更新時間:

Buy Me A Coffee

系列章節 第 10 篇 / 共 27 篇

0 %
MIT Licensed | Copyright © 2025-present Wen-Hsiu's Blog
Photo by Federica Galli on Unsplash