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";
}

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.

Further reading

Problem with a question

HTML & CSS · Senior · question 6

Test yourself

Take the HTML & CSS · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz