Lesson 48 of 50
cssCSS for Performance – Avoiding Layout Thrash
9 mins
Course progress96%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 48 of 50
css9 mins
Keep these ideas in mind as you work through the lesson.
A layout thrash happens when JavaScript reads a layout‑dependent property (e.g., offsetHeight) and then writes a style that forces the browser to re‑calculate the layout. Repeating this each frame kills performance.
requestAnimationFrame.
let latestWidth;
function read() { latestWidth = element.offsetWidth; }
function write() { element.style.setProperty('--width', `${latestWidth}px`); }
requestAnimationFrame(() => { read(); write(); });
transform & opacity – they stay on the compositor layer.contain property to tell the browser the element is self‑contained.
.widget { contain:layout style paint; }
This prevents changes inside .widget from triggering re‑flows elsewhere.width:100% on elements that also have margin or border if box-sizing:border-box isn’t applied.requestAnimationFrame or a small timeout.containheader {
position:sticky; top:0; background:#fff; z-index:10;
contain:layout; /* the header’s size never influences the rest */
}
@keyframes on transform/opacity, let the browser handle it – it runs on the compositor without JavaScript.transform or opacity.contain is applied to isolated widgets (modals, carousels).object-fit:cover and are appropriately sized.contain is supported in Chrome 71+, Edge 79+, Safari 12+, and Firefox 44+ (partial). Use a fallback (overflow:hidden) for older browsers if needed.