Don’t Attach Tooltips Directly to document.body

Atif Afzal writes about a better home for tooltips: a <div> that stays on the page permanently, with tooltips added to and removed from it. Moving the tooltips out of <body> and into that container turned out to perform much better.

The usual motive for keeping tooltips near the top of the DOM isn't performance. It's positioning: sitting high up lets you place them with absolute positioning exactly where they're needed, without wrestling hidden overflow or relative parents.

Afzal was surprised that a separate container alone fixed the performance, with no CSS contain property involved. Next came the harder part — explaining why. He initially suspected an internal browser heuristic optimizing Recalculate Style, but found no such black magic.

The real mechanism is avoiding forced style recalculations. As he puts it:

The tooltip container is not visible in the page, so modifying it doesn’t invalidate the complete page render tree. If the tooltip container would have been visible in the page, then the complete render tree would be invalidated but in this case only an independent subtree was invalidated. Recalculating Style for a small subtree of 3 doesn’t take a lot of time and hence is faster.

Because popper.js appears to be involved, Afzal advises being deliberate about where components land. On CodePen, toast messages come from react-hot-toast, their only third-party component at the time of writing. He checked, and the messages get tucked into a <div> of CodePen's own — and the library does it too — so that setup is in the clear.

CSS-Tricks star logo