Using CSS to Stop Element Scrolling out of View

The aim is to allow the content in the sidebar to scroll upwards, alongside the main content until it reaches the top of the screen. It will then hold position whilst the main body of content continues to scroll.

This is like setting a fixed position, but it is allowed to scroll when there is space above.

Consider a page divided into two parts: main content; and right sidebar. When the page scrolls these two should travel upwards. Ultimately for long content the main content div will pass on upwards the earlier content disappearing from view. Typically the content within the sidebar comprises links to recent or related content and maybe links which are to be encouraged to be followed. Keeping this within view would be desirable.

The scrolling of the right hand sidebar should stop once the top reaches the top of the screen. Keeping it within view.

It’s an easy implementation using CSS which would require additional work with JavaScript or jQuery to calculate the position and to stop or enable the scrolling.

There are some really useful CSS options available. Setting the element as sticky which ensures that the element doesn’t pass outside the browser window, whilst it’s within the parent element.

position: sticky;
top: 0;

If you are using Bootstrap this can be achieved by adding the class sticky-top to the element.

The sticky parameter for the CSS position property controls how the element reacts when the associated point, defined by top or bottom, is reached.

As an example an element may be given a value for top of 0.

When the containing element scrolls to the top of the page this element will hold position. Or until the element it’s in passes above the top of the browser.