When the content inside an element is really large, it might overflow its boundaries.
The easiest and most commonly used approach to avoid this problem is to simply add a vertical scroll bar to the element whenever the content is overflowing.
This behavior can easily be controlled using the overflow property. The overflow property is actually a shorthand of the overflow-x and overflow-y properties.
To make the div vertically scrollable simply set the overflow property to auto
. This will add a vertical as well as horizontal scroll bar to the element whenever the content overflows.
Before using the overflow property make sure that the element has a fixed height. Otherwise, the overflow property will not affect the element.
Here is an example:
Example:
div{ width: 300px; height: 150px; overflow: auto; border: 2px solid red; padding: 10px; }
You can also add vertical and horizontal scroll bars by individually setting the overflow-y and overflow-x property to auto
.
Here is the same example as above but with individual properties:
Example:
div{ width: 300px; height: 150px; overflow-x: auto; overflow-y: auto; border: 2px solid red; padding: 10px; }
Make the div only Vertically Scrollable
If you want to make the div element only vertically scrollable when the content overflows, simply set the overflow-y to auto
and overflow-x to hidden
.
This will only add a vertical scroll bar whenever required and keep the horizontal scroll bar hidden.
See this example:
Example:
div{ width: 300px; height: 150px; overflow-x: hidden; overflow-y: auto; border: 2px solid red; padding: 10px; }