0

I have a question similar to the one asked before here Horizontal Scrolling? and Horizontal scroll in DIV with many small DIV's inside (no text) .

But an additional constraint is that I will be adding div programatically and may not know the size of each div upfront. In this case is it possible to achieve horizontal scroll?

How should the HTML/CSS look?

Community
  • 1
  • 1
Player
  • 378
  • 2
  • 7

1 Answers1

1

The button in this example will insert a new div with a randomized width, eventually resulting in horizontal scrolling. Points of interest: white-space: nowrap and overflow: scroll on the container; display: inline-block on the child divs.

var container = document.getElementById('items');

function addItem() {
  var d = document.createElement('div');
  d.style.width = Math.floor(Math.random() * 100) + 20 + 'px';
  container.appendChild(d);
}
#items {
  white-space: nowrap;
  overflow:scroll;
}

#items div {
  display: inline-block;
  border: 1px solid red;
  height: 50px;
}
<button onclick="addItem()">Add Item</button>

<div id="items"></div>
ray
  • 26,557
  • 5
  • 28
  • 27