Creating an Auto-Scrollable Element with CSS

Alberto Iannaccone
2 min readJan 31, 2023

Have you ever wanted to implement a chat or a log display in your web page that automatically scrolls to show the newest content as soon as it is added? This can easily be achieved with a few lines of CSS.

Auto-scrolling HTML element showing continuously added content

In this tutorial, I’ll show you how to create an auto-scrollable element with CSS that automatically scrolls down to show the newest content as soon as it is added.

Here is the CSS code that you’ll need:

.autoscrollable-wrapper {
overflow: auto;
max-height: 100%;
display: flex;
flex-direction: column-reverse;
}

And here is the HTML code:

<div class="autoscrollable-wrapper">
<div class="autoscrollable-content">
<!-- put here the content that needs to automatically scroll -->
</div>
</div>

Let’s go through each line of the CSS code to understand what it does.

  • The overflow property is set to auto, which means that the element will have a scrollbar if its content overflows.
  • The max-height property is set to 100%, which means that the height of the element will be limited to 100% of the parent element. Setting a max-height instead of height is useful because it allows the element to dynamically adjust its height, keeping the first content at the top and allowing new content to appear at the bottom. If you want the content to immediately show at the bottom, you can use height instead of course.
  • The display property is set to flex, which means that the element will be a flex container. The flex-direction property is set to column-reverse, so that the flex items will be laid out vertically and in reverse order. That’s what is causing new content to appear at the bottom and triggering an automatic scroll down.

In short, the use of flex and flex-direction: column-reverse in the CSS is what makes the auto-scrollable element stay scrolled to the bottom and show the newest content as it is added.

I’ve created a CodePen example with some JavaScript code that just keeps printing text in the element to show that it scrolls down as new text is added.

References

--

--