QA
Senior LevelCSS & Modern Layouts

What is CSS layout thrashing and how do you prevent forced synchronous reflows?

❓ Interview Prompt: Explain how reading layout properties after write operations causes forced reflows and performance degradation.

Layout thrashing occurs when JavaScript interleaves DOM writes (style changes) with DOM reads (layout property queries), forcing the browser to recalculate layout synchronously between each operation:

The Pattern:

```

element.style.width = '100px'; // Write

const h = element.offsetHeight; // Read → forces synchronous layout!

element.style.width = '200px'; // Write

const w = element.offsetWidth; // Read → forces another layout!

```

Prevention:

1
Batch reads first, then batch writes: Read all geometric properties first, then apply all style changes.
2
Use `requestAnimationFrame()`: Defer writes to the next frame.
3
Use CSS containment: contain: layout limits reflow scope.

Code Implementation Example

css
/* CSS containment to limit reflow scope */
.widget {
  contain: layout style;
}

/* Use transform instead of top/left to avoid layout triggers */
.animated {
  transform: translateX(var(--x)) translateY(var(--y));
  will-change: transform;
}
💡CSS containment and transform-based positioning to avoid layout thrashing.
🎯 Interview Key Takeaway

Batch all DOM reads before writes and use transform instead of top/left to avoid forced synchronous layouts.

#Layout Thrashing#Performance#Reflow#Senior
Back to all CSS & Modern Layouts Questions→

More CSS & Modern Layouts Interview Questions

Beginner LevelCSS & Modern Layouts

What is the CSS Box Model and how do content, padding, border, and margin interact?

Beginner LevelCSS & Modern Layouts

How does CSS specificity and the cascade determine which styles are applied?

Beginner LevelCSS & Modern Layouts

What are the differences between display: block, inline, inline-block, flex, and grid?