How to Use Overflow Scroll in CSS for Scrollable Content
Use the CSS property
overflow: scroll; on a container to add scrollbars when its content is larger than the container. This forces both horizontal and vertical scrollbars to appear, allowing users to scroll through the hidden content.Syntax
The overflow property controls what happens when content overflows its container. Using overflow: scroll; forces scrollbars to appear both horizontally and vertically, even if they are not needed.
Parts explained:
overflow: The CSS property controlling overflow behavior.scroll: The value that always shows scrollbars.
css
selector {
overflow: scroll;
}Example
This example shows a fixed-size box with content larger than the box. Using overflow: scroll; adds scrollbars so you can scroll to see all content.
css
html, body {
height: 100%;
margin: 0;
font-family: Arial, sans-serif;
}
.container {
width: 300px;
height: 150px;
border: 2px solid #333;
overflow: scroll;
padding: 10px;
box-sizing: border-box;
}
.content {
width: 500px;
height: 300px;
background: linear-gradient(45deg, #6b8ce3, #e36b6b);
color: white;
padding: 10px;
box-sizing: border-box;
}Output
<div class="container"><div class="content">This box is larger than the container, so scrollbars appear to let you see all content.</div></div>
Common Pitfalls
Common mistakes when using overflow: scroll; include:
- Scrollbars always show, even if content fits, which can look cluttered.
- Not setting a fixed size on the container, so scrollbars never appear.
- Using
overflow: auto;might be better if you want scrollbars only when needed.
css
/* Wrong: No fixed size, so no scrollbars appear */ .container { overflow: scroll; border: 1px solid black; } /* Right: Fixed size with overflow scroll */ .container { width: 200px; height: 100px; overflow: scroll; border: 1px solid black; }
Quick Reference
Tips for using overflow: scroll;:
- Use on containers with fixed width and height.
- Scrollbars always show, which can be distracting.
- Consider
overflow: auto;to show scrollbars only when needed. - Use
overflow-xoroverflow-yto control horizontal or vertical scrolling separately.
Key Takeaways
Use
overflow: scroll; to always show scrollbars on overflowing content.Set fixed width and height on containers to enable scrolling.
Scrollbars appear even if content fits, which may affect design.
Use
overflow: auto; for scrollbars only when needed.Control horizontal or vertical scroll separately with
overflow-x and overflow-y.