Open In App

Making a div Vertically Scrollable using CSS

Last Updated : 24 Apr, 2025
Summarize
Comments
Improve
Suggest changes
Share
12 Likes
Like
Report

The overflow property in CSS controls how content that goes beyond an element's boundaries is handled. It can either hide the extra content or add scrollbars so users can scroll to see more without leaving the current view. This helps display large amounts of content, such as text, images, or tables, in web applications.

By using the methods given below, we can make a div vertically scrollable.

1. Using the overflow-x and Overflow-y Property

The overflow-x and overflow-y properties are used to control horizontal and vertical scrolling, respectively.

Now, let us understand with the help of the example:

Output:

Overflow-XX

In this Example:

  • The <style> tag within the <head> section contains the CSS styles for the overflow behavior.
  • The container is sized to be 300px by 150px, while the content inside it is intentionally larger, causing both horizontal and vertical overflow.
  • overflow-x: scroll ensures horizontal scrolling is enabled.
  • overflow-y: scroll enables vertical scrolling when the content overflows.

2. Using overflow:auto Property

The overflow: auto property adds scrollbars only when the content doesn’t fit inside the box. Since the text is longer than the box’s height, a vertical scrollbar appears so you can scroll and read everything easily.

Now, let us understand with the help of the example:

Output

Making-a-div-vertically-scrollable-using-CSS
Making a div vertically scrollable using CSS

In this Example:

  • The .container is given a fixed width of 300px and height of 110px, with margin and padding to add space inside and around the container.
  • The overflow: auto; property ensures that scrollbars appear only if the content inside the .container exceeds the container’s set dimensions. It shows a vertical scrollbar if the content overflows vertically.
  • The background color of the .container is set to rgb(143, 226, 143), giving it a light green shade to distinguish it from other content.
  • With the vertical overflow in this case, when the content exceeds the container’s height, the overflow: auto; ensures that a scrollbar is displayed for easy navigation through the content.

Conclusion

Making a div vertically scrollable using CSS is a simple and effective way to manage content that exceeds a container's height. By setting a fixed height and using the overflow-y property, you can easily implement vertical scrolling. Additionally, you can enhance the user experience with smooth scrolling and custom scrollbar styles. By following best practices and considering responsive design, you can create scrollable containers that work well across all devices.


Similar Reads