3

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

Kevin Farrugia
  • 6,431
  • 4
  • 38
  • 61

1 Answers1

1

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
David Bradshaw
  • 11,859
  • 3
  • 41
  • 70
  • Safari keeps `scrollY` constant. On Chrome, the `scrollY` increases on each poll. To have the content maintain the same position, you would need to do `scrollY = y + elementHeight`; however I cannot get the elementHeight until it is painted to the screen. – Kevin Farrugia May 24 '21 at 16:04
  • If you paste the element, read the value and then update scrollY it will be fast enough for the user not to notice – David Bradshaw May 24 '21 at 18:07