Read more

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

Henning Koch
September 22, 2018Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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>.
Posted by Henning Koch to makandra dev (2018-09-22 09:23)