How to Add a Scrollbar in CSS
Browsers are only Web objects that can have the ability to display scrollbars. Web developers add a scrollbars to div containers as well by adjusting their CSS overflow property values. Since divs can contain other Web page elements, adding a scrollbar to a div allows users to scroll through those elements as well. By creating a JavaScript function that modifies a divs overflow value in real time, you can make scrollbars appear as users interact with your Web application.
Instructions
-
-
1
Paste the code shown below into the body section of one of your HTML documents:
<div id="testDiv1" class="smallDiv">
aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa
aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa
aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa aa
</div><input type="button" value="Add Scrollbar" onclick="manageScollbar('testDiv1', 'show');" />
<input type="button" value="Remove Scrollbar" onclick="manageScollbar('testDiv1', 'hide');" />This code creates a div block containing sample text. The div's id is "testDiv1." The div also references a CSS class named "smallDiv." This class creates a small div that cannot hold all the text. The first button control calls a JavaScript function named "manageScrollbar." The button passes the div's id value to that function as well as the word "show." The second button calls the same JavaScript function. That button passes the word "hide" to the function. The two buttons show and hide the div's scrollbar when clicked.
-
2
Paste this CSS code into the document's style section to create the smallDiv CSS class.
.smallDiv {height:100px; width:100px;}
-
-
3
Add the JavaScript code shown below to your document's script section:
function manageScollbar(div, action) {
divObj = document.getElementById(div);
if (action == "show")
divObj.style.overflow = "scroll";
else
divObj.style.overflow = "hidden";}
This code sets the div's overflow property to "scroll" if users click the "Show Scrollbar" button. Otherwise, it sets the overflow property to "hidden."
-
4
Save your HTML document and view it in a browser. The div containing text appears. Click "Show Scrollbar." The code runs and makes a scrollbar appear. Click "Hide Scrollbar" to make the scrollbar disappear.
-
1