ArticleZip > Scrollable Div To Stick To Bottom When Outer Div Changes In Size

Scrollable Div To Stick To Bottom When Outer Div Changes In Size

Have you ever come across a scenario where you wanted a scrollable section to stick to the bottom of a larger container but found it challenging as the outer container's size kept changing dynamically? In this article, we will guide you through a simple and effective solution that involves using HTML, CSS, and a bit of JavaScript magic to achieve this desired behavior.

To implement a scrollable `div` that sticks to the bottom of its container while dynamically adjusting to changes in the size of the outer `div`, we will need to leverage a few key properties and event listeners.

Let's start with the HTML structure. You will need a parent container `div`, which we'll call the outer `div`, and a child `div` that will serve as the scrollable element.

Html

<div class="outer-container">
    <div class="scrollable-div">
        <!-- Your content goes here -->
    </div>
</div>

Next, let's move on to the CSS styling. The outer container should have a defined height and relative positioning, while the scrollable `div` should be styled to stick to the bottom and overflow when necessary.

Css

.outer-container {
    height: 300px; /* Set the desired height */
    position: relative;
}

.scrollable-div {
    position: absolute;
    bottom: 0;
    width: 100%;
    overflow-y: auto;
}

Now comes the JavaScript part. To make the scrollable `div` stick to the bottom as the outer container changes size, we can use the following simple script. This script ensures that the scrollable `div` remains at the bottom whenever the outer container's size changes.

Javascript

const outerContainer = document.querySelector('.outer-container');
const scrollableDiv = document.querySelector('.scrollable-div');

const observer = new ResizeObserver(() =&gt; {
    scrollableDiv.scrollTop = scrollableDiv.scrollHeight;
});

observer.observe(outerContainer);

By utilizing the `ResizeObserver` API, we can track changes in the size of the outer container and adjust the scroll position of the inner `div` accordingly, ensuring that it stays pinned to the bottom.

And there you have it! With this approach, you can create a scrollable `div` that sticks to the bottom of a dynamically resizing container with ease. Feel free to customize the styles and adapt the behavior to suit your specific requirements.

We hope this article has provided you with a clear and practical solution to implement a scrollable `div` that sticks to the bottom when the outer `div` changes in size. Happy coding!