CSS Performance Tip #2 Browser Reflow & Repaint

This post has been inspired from:

Reflows & Repaints: CSS Performance making your JavaScript slow?

What is Repaint and Reflow?
A repaint occurs when changes are made to an elements skin that changes visibility, but do not affect its layout. Examples of this include outline, visibility, or background color. According to Opera, repaint is expensive because the browser must verify the visibility of all other nodes in the DOM tree. A reflow is even more critical to performance because it involves changes that affect the layout of a portion of the page (or the whole page). Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM.

Reflows are very expensive in terms of performance, and is one of the main causes of slow DOM scripts, especially on devices with low processing power, such as phones. In many cases, they are equivalent to laying out the entire page again.

How to avoid reflows or at least minimize their impact on performance?

  • Change classes on the element you wish to style (as low in the dom tree as possible)
  • Avoid setting multiple inline styles
  • Apply animations to elements that are position fixed or absolute. They don’t affect other elements layout, so they will only cause a repaint rather than a full reflow. This is much less costly.
  • Trade smoothness for speed. What they mean by this is that you may want to move an animation 1 pixel at a time, but if the animation and subsequent reflows use 100% of the CPU the animation will seem jumpy as the browser struggles to update the flow. Moving the animated element by 3 pixels at a time may seem slightly less smooth on very fast machines, but it won’t cause CPU thrashing on slower machines and mobile devices.
  • Avoid tables for layout (or set table-layout fixed)
  • Avoid JavaScript expressions in the CSS (IE only)

Leave a comment