In this post, we will go over how to make an HTML scrollable div. To do this we will use the CSS overflow property and set its value to either scroll or auto.
.scrollable-div1 { overflow: scroll; } .scrollable-div2 { overflow: auto; }
The main difference between overflow: scroll and overflow: auto is that scroll will always show the scroll bars, where auto will only show them when needed.
Let’s say I have the following HTML:
This is a scrollable div
If we want to make “#div1” scrollable in the example above, we would need to set its CSS overflow property to scroll, and usually give it a fixed height and width.
#div1 { height: 100px; width:100px; overflow: scroll; }
Examples of HTML Scrollable divs
This first example will just show a simple HTML scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
The code above will produce the result below:
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
If we want to get rid of the horizontal scroll bar, we can just use the overflow-y property instead of overflow, and set it to scroll.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
The code above will produce the result below:
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
This is a scrollable div.
HTML scrollable div with Dynamic Content
Our final example will show how we can use a scrollable div to only show the scroll bar when more content is added to the scrollable div.
Let’s say I have the following HTML:
This is a scrollable div
Keep clicking the button below to add enough divs to show the scrollbar.
Add text
We will then use the jQuery appendTo() method to keep adding HTML divs to our scrollable div.
$("#click-me").click(function(){
$('This is a scrollable div').appendTo("#div5");
});
The final code and output for this example of how to have an HTML scrollable div is below:
Code Output:
Keep clicking the button below to add enough divs to show the scrollbar.
Full Code:
This is a scrollable div
Keep clicking the button below to add enough divs to show the scrollbar.
Add text
Hopefully this article has helped you to understand how to make an HTML scrollable div.