Creating an Auto-Scrollable Element with CSS
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.
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 toauto
, which means that the element will have a scrollbar if its content overflows. - The
max-height
property is set to100%
, which means that the height of the element will be limited to 100% of the parent element. Setting amax-height
instead ofheight
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 useheight
instead of course. - The
display
property is set toflex
, which means that the element will be a flex container. Theflex-direction
property is set tocolumn-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
- Stack Overflow Answer — Original solution that inspired this tutorial.