In a chat application, it is common to have a scrollable div within another div that contains the conversation history. When the outer div changes in size, such as when the input field at the bottom grows or shrinks, the scrollable div should maintain its position at the bottom of the conversation.
Using the flex-direction: column-reverse; property on the outer div, you can achieve this behavior without any JavaScript. This property essentially flips the order of the child elements, placing the scrollable div at the bottom.
.outer-div { display: flex; flex-direction: column-reverse; } .scrollable-div { flex: 1; overflow: auto; }
However, this solution has a drawback: it may cause the scrollbar to disappear in certain browsers like Firefox, IE, and Edge.
To fix the hidden scrollbar issue, you can add the following CSS:
/* Reset webkit, including edge */ .scrollable-div-text { overflow: visible; } @supports (-ms-accelerator: true) { .scrollable-div-text { overflow: auto; } }
This effectively creates a second scrollable div within the first, ensuring that the scrollbar remains visible.
// Check if at bottom of scrollable div function scrollAtBottom(el) { return (el.scrollTop + 5 >= (el.scrollHeight - el.offsetHeight)); } // Update scroll position if at the bottom function updateScroll(el) { el.scrollTop = el.scrollHeight; } // Function to resize input and adjust scroll position if needed function resizeInput() { const scrollableDiv = document.getElementById('scrollable-div'); const input = document.getElementById('input'); // Toggle input height input.style.height = input.style.height === '40px' ? '120px' : '40px'; // Check if scrolled to the bottom and update scroll position if needed if (scrollAtBottom(scrollableDiv)) { updateScroll(scrollableDiv); } }
In the above script, the resizeInput() function checks if the scrollbar is at the bottom of the scrollable div and adjusts the scroll position if needed.
The above is the detailed content of How to Keep a Scrollable Div Stuck to the Bottom of a Resizable Outer Div?. For more information, please follow other related articles on the PHP Chinese website!