On Safari, the content in the viewport shifts when the DOM is updated outside of the visible viewport

964 views Asked by At

On Google Chrome when adding an element to the DOM above the user's viewport, the content in the viewport does not shift, while on Safari it does (equal to the height of the new element).

How is it possible to not have the content shift on Safari following an update outside of the viewport?

Edit (2021-06-02): I have discovered this behaviour is called scroll anchoring and more details may be found on https://github.com/WICG/ScrollAnchoring and https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-anchor/Guide_to_scroll_anchoring


In the demo video below, an item is added to the top of the list (every 4 seconds). As the item is added (highlighted in blue) the content in the viewport (mimicked using the scrollable area) shifts downwards causing a layout shift.

Demonstration of layout shift

1

There are 1 answers

2
David Bradshaw On

The simplest solution is likely to be to read window.scrollY before you make the change to your page and then set it back to that value after you have inserted your new element

const y = window.scrollY
updatePage()
window.scrollY = y