HTML & CSS · Senior · Question 6 of 75
What is layout thrashing (forced synchronous layout)?
for (const el of items) {
el.style.width = box.offsetWidth + "px";
}- ✓Correct answer: Repeated layout recalculation caused by interleaving reads and writes in a loop
- 2When a CSS animation of
widthrecalculates layout every frame - 3A browser error caused by an overly deep DOM tree on the page
Explanation
Reading offsetWidth after writing a style forces the browser to recalculate layout synchronously to return an up-to-date value. In a loop this happens on every iteration. The fix is to read all values first, then write (batch reads/writes), or move the read out of the loop. Libraries like fastdom help too.