CSS: How to Make a div Scrollable Vertically and Horizontally

Sometimes, a <div> contains more content than it can visibly display — whether that’s wide tables, long paragraphs, or overflowing media. Instead of letting the content spill out, you can enable both vertical and horizontal scrolling within the div for better layout control and a cleaner user experience.

This blog post will show you how to make a div scrollable in both directions using CSS — with practical examples and best practices.


✅ Step 1: Use the overflow Property

To enable scrolling, CSS provides the overflow property. When set to scroll or auto, this property allows the content to scroll when it overflows the container.


✅ Example: Scrollable in Both Directions

📌 CSS:

.scroll-box {
  width: 300px;
  height: 200px;
  overflow: auto;  /* scrollbars appear only when needed */
  border: 1px solid #ccc;
  white-space: nowrap; /* prevents content from wrapping */
}

📌 HTML:

<div class="scroll-box">
  <!-- Add wide and tall content here -->
  <p>This content might overflow both vertically and horizontally if it's long enough. Try resizing or adding more lines and extra-long words_with_no_breaks.</p>
</div>

✅ Result:

The <div> now scrolls horizontally and vertically when content overflows.


🧠 Understanding the Properties

  • overflow: auto;
    Adds scrollbars only when content exceeds the div’s size.
  • overflow: scroll;
    Forces scrollbars to appear even when content fits — not recommended for clean UI.
  • white-space: nowrap;
    Prevents automatic line breaks, forcing horizontal overflow if content is wide.

💡 Use white-space: normal; if you want text to wrap normally but still scroll if it grows too tall.


✅ Force Scrollbars to Always Appear

.scroll-box {
  width: 300px;
  height: 200px;
  overflow: scroll;
}

This forces both vertical and horizontal scrollbars to appear regardless of content size. Not ideal for aesthetics, but sometimes useful during development.


✅ For Tables or Images

If you have wide tables or images, wrapping them in a scrollable <div> helps maintain layout:

<div class="scroll-box">
  <table>
    <!-- Very wide table rows/columns -->
  </table>
</div>

🧾 Summary

GoalCSS Rule
Scroll when neededoverflow: auto;
Always show scrollbarsoverflow: scroll;
Prevent text wrappingwhite-space: nowrap;
Scroll vertically onlyoverflow-y: scroll; overflow-x: hidden;
Scroll horizontally onlyoverflow-x: scroll; overflow-y: hidden;

🧠 Conclusion

Enabling both vertical and horizontal scrolling in a <div> is easy and efficient using overflow: auto or overflow: scroll. Whether you’re handling dynamic content, large tables, or embedded media, these CSS properties give you precise control over your layout.


Pro Tip: Always test your scrollable divs across devices — especially on mobile — and ensure content inside remains usable and accessible.

Sharing Is Caring:

Leave a Comment