Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I break inline-blocks into 2 lines maximum?

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading