I have an indefinite number of blocks that I want to place inside a container and have them break into 2 lines maximum and then be able to scroll horizontally across those 2 lines of blocks.
I'm trying the code you see in the snippet but it's not working. It's placing all blocks in one single line.
let container = document.getElementById('container')
let numOfBlocks = 20 // could be any number
let blockSize = 200
let blockRightMargin = 10
let maxContainerWidth = Math.ceil(numOfBlocks/2)*(blockSize blockRightMargin)
while (numOfBlocks) {
let block = document.createElement('div')
block.className = 'block'
container.appendChild(block)
numOfBlocks--
}
container.style['max-width'] = maxContainerWidth 'px'
#horizontal-scroller {
position: relative;
float: left;
height: auto;
width: 100%;
max-width: 420px;
overflow-x: auto;
}
#container {
position: relative;
float: left;
height: auto;
width: auto;
text-align: left;
font-size: 0;
white-space: nowrap;
}
.block {
display: inline-block;
width: 200px;
height: 200px;
margin-right: 10px;
margin-bottom: 10px;
background: lime;
}
<div id="horizontal-scroller">
<div id="container"></div>
</div>
CodePudding user response:
Use CSS grid:
#horizontal-scroller {
position: relative;
max-width: 420px;
overflow-x: auto;
display: grid;
grid-template-rows: 1fr 1fr; /* 2 rows */
grid-auto-flow: column;
gap: 10px;
}
#horizontal-scroller > div {
width: 150px;
height: 150px;
background: lime;
}
<div id="horizontal-scroller">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>