How to Create a Scrollable Div in CSS: Simple Guide
To create a scrollable
div in CSS, set a fixed height or width and use overflow: auto; or overflow: scroll;. This makes the content inside the div scrollable when it exceeds the set size.Syntax
Use the overflow property to control scrolling behavior. Common values are:
overflow: auto;- shows scrollbars only when needed.overflow: scroll;- always shows scrollbars.overflow-xandoverflow-y- control horizontal and vertical scrolling separately.- Set a fixed
heightorwidthto limit the visible area.
css
div {
width: 300px;
height: 150px;
overflow: auto;
border: 1px solid #ccc;
}Example
This example shows a div with fixed size and scrollable content inside. When the content is taller than the div, a vertical scrollbar appears.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Scrollable Div Example</title> <style> .scrollable { width: 300px; height: 150px; overflow: auto; border: 2px solid #007BFF; padding: 10px; font-family: Arial, sans-serif; box-sizing: border-box; } </style> </head> <body> <div class="scrollable"> <p>This is a scrollable div. It has a fixed height and width. When the content inside is bigger than the box, scrollbars appear so you can see all the content.</p> <p>Try adding more text or elements to see the scrollbar in action.</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sit amet eros nec urna cursus blandit.</p> </div> </body> </html>
Output
A rectangular box 300px wide and 150px tall with a blue border containing multiple paragraphs. Vertical scrollbar appears on the right side allowing scrolling through the text.
Common Pitfalls
Common mistakes when creating scrollable divs include:
- Not setting a fixed height or width, so the div expands instead of scrolling.
- Using
overflow: visible;which disables scrolling. - Forgetting to set
box-sizing: border-box;which can cause sizing issues. - Expecting scrollbars on inline elements instead of block elements.
css
/* Wrong: No fixed height, no scrolling */ div { overflow: auto; border: 1px solid black; } /* Right: Fixed height enables scrolling */ div { height: 150px; overflow: auto; border: 1px solid black; box-sizing: border-box; }
Quick Reference
Summary tips for scrollable divs:
- Always set a fixed
heightorwidthto limit the visible area. - Use
overflow: auto;for scrollbars only when needed. - Use
overflow-xoroverflow-yto control horizontal or vertical scrolling separately. - Remember to test on different browsers and devices for consistent behavior.
Key Takeaways
Set a fixed height or width on the div to enable scrolling.
Use overflow: auto to show scrollbars only when content overflows.
overflow-x and overflow-y control horizontal and vertical scroll separately.
Without fixed size, div expands and no scrollbar appears.
Test scrollable divs on different devices for best user experience.