Let’s imagine a scenario that you might have encountered while writing HTML codes.
A situation might occur where you have the whole width of the screen available for taking, but not the whole height. Say you have a large chunk of text you wish to embed into your page. You can easily do that if the div that will contain the text is vertically scrollable.
A common use case of this is the embedded code windows on pages where a certain height has been set for the div and the code line exceeds this height. The code window in this kind of situation is usually made scrollable.
To achieve this very useful functionality:
CSS has a property called overflow
, which has many values like:
auto
: Indicates that there should be a scroll bar in the x or y-axis, depending on where the display is chopped.
hidden
: The overflow should be chopped away, making it invisible.
scroll
: This provides a scroll bar for viewing clipped content.
visible
: This leaves the overflow to display outside the box of the div.
We can use a combination of overflow-x
and overflow-y
to place the scrollbar vertically, horizontally, or both. For the vertical scrollbar, overflow-x:hidden
and overflow-y:auto
will be set in the CSS file, and vice versa for the horizontal scrollbar.
Below are some code examples.
<html><head><style>h1 {color:Green;}div.scroll {margin:4px, 4px;padding:4px;background-color: green;width: 500px;height: 110px;overflow-x: hidden;overflow-y: auto;text-align:justify;}</style></head><body><center><h1>Goodnews</h1><div class="scroll">Aliquam erat volutpat.Pellentesque vel augue ut ipsumdignissim ornare. Donec commodo fringillaneque, sed aliquet lacus dapibus quis.Integer tempus faucibus justo in feugiat.Etiam feugiat orci nec tortor faucibus, necdictum justo eleifend. Curabitur fringillaposuere risus, vel elementum lorem sagittis et.Aliquam tincidunt consequat nibh ut sollicitudin.am sit amet sodales arcu, et ultricies purus. Aliquammolestie urna id metus vehicula, ac venenatis sapienaccumsan. In commodo posuere dapibus. Nulla hendrerit,enim at finibus semper,ipsum dui faucibus leo,non commodo turpis neque ut est.</div></center></body></html>
The code above implements the scrollbar as described in method 1.
To implement method 2, just change the CSS portion of this code by removing overflow-y
and overflow-x
, and replace them with overflow:auto
.
The output from the two codes will be the same and will look like the image below.
You can see the scrollbar in the right corner of the div.