I have a div that is only 300 pixels big and I want it to when the page loads scroll to the bottom of the content. This div has content dynamically added to it and needs to stay scrolled all the way down. Now if the user decides to scroll up I don't want it to jump back to the bottom until the user scrolls all the way down again.
Is it possible to have a div that will stay scrolled to the bottom unless the user scrolls up and when the user scrolls back to the bottom it needs to keep itself at the bottom even when new dynamic content is added. How would I go about creating this?
I was able to get this working with CSS only.
The trick is to use flex-direction: column-reverse
The browser treats the bottom like its the top. Assuming the browsers you're targeting support flex-box
, the only caveat is that the markup has to be in reverse order.
Here is a working example:
.container {
height: 100px;
overflow: auto;
display: flex;
flex-direction: column-reverse;
}
<div class="container">
<div>Bottom</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Hi</div>
<div>Top</div>
</div>