Flex grid with dynamic content

Viewed 54

I need a solution, most likely using flexbox, for a grid of content that needs to be flexible depending on how many objects are created within the CMS. I know flex can be used to create each individual option as shown below, but is there a way I can use flex to show the layout without knowing the total number of divs?

enter image description here

2 Answers

is there a way I can use flex to show the layout without knowing the total number of divs?

Just apply flex:auto on all child divs:

.row{
  display:flex;
  flex-wrap:wrap;
  width:330px;
}
.col{
  background-color:#D0D1D2;
  width:100px;
  height:100px;
  margin:5px;
  flex:auto;
}
<div class="row">
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
  <div class="col"></div>
</div>

Demonstration example that lets you choose the number of divs:

range.addEventListener('input', function(){
  row.innerHTML = '<div class="col"></div>'.repeat(this.value);
  this.nextElementSibling.textContent = this.value;
})
.row{
  display:flex;
  flex-wrap:wrap;
  width:330px;
}
.col{
  background-color:#D0D1D2;
  width:100px;
  height:100px;
  margin:5px;
  flex:auto;
}
<div class="row" id="row">
  <div class="col"></div>

</div>

<input type="range" id="range" value="1" min="1" max="10"><output>1</output>

// You can remove this unless you want to
// programmatically add or remove divs
var noOfDivs = 1;
function addDiv() {
  noOfDivs++;
  render();
}
function removeDiv() {
  noOfDivs = Math.max(0, noOfDivs - 1);
  render();
}
function render() {
  document.getElementById("container").innerHTML = '';
  for(var i = 0; i < noOfDivs; i++) {
    document.getElementById("container").innerHTML += "<div class = 'inner'></div>"
  }
}
#container {
  display: flex;
  flex-flow: row wrap;
  margin-bottom: 5px;
}

#container div.inner {
  background: #aaa;
  height: 100px;
  width: 100px;
  margin: 2px;
  flex: auto;
}

/*Remove these syles later they are just for the buttons*/
#add-box {
  position: fixed;
  left: 10px;
  top: 10px;
  font-size
}
#remove-box {
  position: fixed;
  left: 80px;
  top: 10px;
  font-size
}
<div id='container'>
  <div class='inner'></div>
</div>
<button onclick='addDiv()' id = 'add-box'>Add box</button>
<button onclick='removeDiv()' id = 'remove-box'>Remove box</button>

Related