Explain Codes LogoExplain Codes Logo

Div with horizontal scrolling only

html
responsive-design
css
scrolling
Alex KataevbyAlex Kataev·Nov 24, 2024
TLDR

Enable horizontal scrolling in a <div> by applying overflow-x:auto; and a fixed width. Implement white-space:nowrap; on content to prevent line breaks. Here's your quick fix:

<div style="overflow-x:auto; width:300px; white-space:nowrap;"> Content that spills outside the 300px underlying stage, scrolling is needed... </div>

To accommodate legacy browsers like IE6 and IE7, consider using inline styles. They keep your solution perceptive to these sometimes finicky veterans.

Scrolling with table content

Integrating tables in your scrollable div comes with certain considerations:

  • Avoid setting overflow-y to hidden to sidestep unintended layout disruptions.
  • Employ white-space: nowrap; with table cells, ensuring content does not wrap and preserves horizontal scrolling.

For table layouts:

<div style="overflow-x: auto; width: 300px;"> <table> <tr> <td style="white-space: nowrap;"> Never-ending content straight ahead! </td> </tr> </table> </div>

Employing flexbox layouts

Flexbox is a potent CSS tool, however, remember our friends IE6 and IE7. If your audience has retired these old friends, feel free to employ flexbox:

div { display: flex; /* Welcome to the flexible era */ overflow-x: auto; /* Horizontal scrolling at your beck and call */ }

With flexbox, tweaking flex-shrink is crucial to prevent flex items from ending up skewing scrolling layouts.

Aligning content smoothly

Content alignment is key to a user-friendly interface. Use margins and display properties for horizontal alignment within the div:

div > * { margin-right: 10px; /* Stylish spacing between items */ display: inline-block; /* Content aligned like well-behaved kids */ }

Handling block elements as inline-block improves the scrolling experience.

Ensuring correct dimensions and overflow

When defining a scrollable area, nailing the dimensions of the div is crucial. A specified width and height confine the scrollable region:

div { width: 300px; /* The quaint little town your long content will scroll through */ height: 200px; /* Like a horizon line, let's focus on sideways exploration */ overflow-x: scroll; /* Being humble and ready for the scroll! */ overflow-y: hidden; /* Thou shalt not pass, vertical scroll */ }

Keep an eye on your content dimensions, to ensure the stage is set for the horizontal performance.

Snippets and live examples

Use JSFiddle or CodePen for real-time testing and visualisation of your scrollable div. It's like watching a live performance of your content.

  • Set background colors for a coherent differentiation of scrollable areas.
  • Explicitly specify content height to avoid unwanted surprises, especially with dynamic content.
  • Investigate examples in the references to get the hang of how this solution is deployed in real-world applications.