How to use scroll position in CSS

If you need to build a CSS rule that includes the browser window’s scroll position, here’s a neat way to do it.

JavaScript

Add the following JavaScript code to the page.

document.documentElement.style.setProperty('--scrollY', window.scrollY + 'px');

window.addEventListener('scroll', () => {
    document.documentElement.style.setProperty('--scrollY', window.scrollY + 'px');
});

This code sets (and automatically updates) a CSS custom property on the root element.

CSS

Use the CSS custom property in your rules.

.example {    
    top: var(--scrollY);
}

Real world example

The “Your progress” column on the left uses position: sticky to stick to the top of the page when scrolling. Within that column, a list of tasks is given a fixed height, with the overflow set to overflow-y: scroll;.

As the sticky column moves upwards, the scrolling list needs to get taller, and this is where having access to the scroll position becomes critical.

The CSS rule for the height of the scrolling list is as follows:

height: calc(100vh - 435px + min(var(--scrollY), 280px));

This translates to:

  • Take the height of the browser window.
  • Subtract 435px (the height of the header, vertical margins, and the “Your progress” subheading).
  • Add the current scroll position, up to a maximum of 280px (after scrolling 280px the sticky column has arrived at the top of the page).