Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
overflow
css

How to add scrollbar to div

Shahpar Khan
svg viewer

Background

In HTML, there is a division container - or <div></div> - that can encapsulate HTML data and elements. This data can then be manipulated using CSS styling and JavaScript. Among other features, you can also add a scrollbar to your div container with CSS.

About overflow

Suppose you make a div container and you predefine some dimensions for it - say 100x200 pixels. Later, when you add data, what if your data cannot be displayed under the preset dimensions? Fortunately, CSS has a property called overflow to deal with clipped data due to restricted dimensions of the container. You can configure overflow using the following values:

  • visible: The overflow is not clipped. It renders outside the element’s box. This is a default.
  • hidden: The overflow is clipped, so the rest of the content will be invisible.
  • scroll: The overflow is clipped, but a scrollbar is added to see the rest of the content.
  • auto: If overflow is clipped, a scrollbar should be added to see the rest of the content.
  • initial: Uses the default value, visible.
  • inherit: Sets the overflow to the value of its parent element

How to add a horizontal scrollbar

Let’s look at the code below:

In the code above, we set the width at 200px and defined the white-space property as nowrap. The container size is now restricted to a width of 200px, and if the text exceeds the container dimensions, it does not wrap onto the next line. Then, we defined overflow-x to scroll, which adds a scrollbar if the text is clipped on the horizontal axis.

How to add a vertical scrollbar

Let’s look at the code below:

Similarly, we have now restricted the height to 100px. To view text that exceeds the height of 100px, we have set the overflow-y property to scroll.

To add scrollbar on both axes, you can add the overflow property instead of adding both overflow-x and overflow-y properties.

RELATED TAGS

html
overflow
css

CONTRIBUTOR

Shahpar Khan
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring