TL;DR: All modern browsers default to using the <html>
element as the main document viewport. In CSS, prefer to set overflow
properties to html
(or
:root
Show archive.org snapshot
).
Scrolling overflowing elements with JavaScript
HTML elements with overflow-y: auto
or overflow-y: scroll
will get a scrollbar when their content is higher than their own height.
When you scroll an element , the element's scrollTop
property is updated with the scrollbar's new position. You can also set element.scrollTop = 30
to scroll the element to a vertical pixel position counted from the top.
Scrolling the main viewport with JavaScript
The browser's main document viewport is also scrollable by default. The element that corresponds to the main viewport is either <html>
(document.documentElement
) or <body>
(document.body
). Which one depends on the browser.
When you want to update the current scrollTop
of the main viewport, you either need to find the correct element or set scrollTop
on both <body>
and <html>
.
Finding the scrolling element
Your JavaScript can call
document.scrollingElement
Show archive.org snapshot
to retrieve the scrollable element for the main viewport.
On Chrome, Firefox and modern Safari, document.scrollingElement
will return the <html>
element.
The behavior varies on legacy browsers that we no longer support:
- Old Safari versions,
document.scrollingElement
will return the<body>
element. - On the legacy Edge engine (EdgeHTML),
document.scrollingElement
will return the<body>
element. - IE11 does not support
document.scrollingElement
, but you can assume its<html>
.
Setting overflow-y for the main viewport with CSS
You can set overflow-y
on either <html>
or <body>
and browsers will silently apply it to whatever scrolling element their implementation uses.
I recommend to set any overflow
property to html
(or
:root
Show archive.org snapshot
).
Don't set overflow-y
for both <html>
and <body>
or funny things will happen.
Setting overflow-y for the main viewport with JavaScript
When your JavaScript wants to change overflow-y
for the main viewport, you should change it on the same element that already has this property set in its CSS styles. Note that this element must not necessarily be the same as scrollingElement()
above.
If you have no control over the CSS styles, your script must look for the right element:
- If
<html>
has anoverflow-y
of eitherscroll
orauto
, use<html>
. - If
<body>
has anoverflow-y
of eitherscroll
orauto
, use<body>
. - If neither has an
overflow-y
set, use<html>
.