Does <html> or <body> scroll the page?

Updated . Posted . Visible to the public. Repeats.

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.

The behavior of document.scrollingElement varies between browsers:

  • On Chrome and Firefox, document.scrollingElement will return the <html> element.
  • Safari, document.scrollingElement will return the <body> element.
  • On Edge, document.scrollingElement will return the <body> element.
  • IE11 does not support document.scrollingElement, but you can assume its <html>.

Summing up, this function should return the correct element on current browsers:

function scrollingElement() {
  return document.scrollingElement || document.documentElement;
}

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.

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:

  1. If <html> has an overflow-y of either scroll or auto, use <html>.
  2. If <body> has an overflow-y of either scroll or auto, use <body>.
  3. If neither has an overflow-y set, use <html>.
Henning Koch
Last edit
Henning Koch
Keywords
html, body, scrolls
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2018-09-22 07:23)