Layout and paint
Learn layout and paint cost.
What is the layout cost?
When an element's size or position changes, the browser computes layout. This is also called reflow. Properties like width, height, margin, top, left and display trigger layout.
Layout is costly: a single change can recompute the whole page's arrangement. That is why animation code avoids layout-triggering properties.
Paint cost and the render pipeline
Paint is the stage where pixels are drawn to the screen. color, background, border-color and box-shadow trigger paint. It is cheaper than layout but still costly.
Composite is the cheapest stage: the browser combines layers. transform and opacity trigger only composite. That is why animations prefer these two. Writing transform: translateX(...) is faster than writing left: ....
Exercise Write the animation with transform
Complete the CSS below. Add transform: translateX(100px) and transition: transform 0.3s ease to the .nav block. The animation then runs without triggering layout.
Show example solution
/* new: transform animation */
.nav {
transform: translateX(100px);
transition: transform 0.3s ease;
}
Test yourself
-
Which change triggers a layout recalculation?
/* which is the most expensive? */ .box { ___: 200px; }- width
- color
- opacity
- transform
Show answer
width — Correct. width changes the box size; the browser recomputes the entire layout.
-
Write the property that does not trigger layout
.nav { /* composite instead of layout */ ____: translateX(100px); }Show answer
.nav { /* composite instead of layout */ transform: translateX(100px); } -
Match each property to the stage it triggers
- width
- Layout recalculation
- color
- Paint redraw
- transform
- Composite (motion)
- opacity
- Composite (alpha)