Francisco Romero
Francisco Romero

Reputation: 13189

Flexbox: display elements with number of columns and rows given

I have an empty div.

<div id="container"></div>

With the following CSS:

#container{
    display: flex;
    position: relative;
    flex-flow: row wrap;
    width: 100%;
}

In which I want to insert more divs via JavaScript but let the user choose how many rows and columns the container will have.

At the moment this is the code I have:

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

var rows = prompt("How much lines do you want?");
var columns = prompt("And how much columns do you want?");

for(var i = 0; i < rows; i++){
   for(var j = 0; j < columns; j++){
      var div = document.createElement("div");
      div.classList.add("square");
      div.innerHTML="<p>" + i + "</p>";
      container.appendChild(div);
   }
}

where square class has the following:

.square{
    flex: 1;
    height: 50px;
}

but all the divs inside the container are displayed in one row.

What I want to do is to set the divs inside the container with the same dimensions that the user inputs, but I cannot get it.

Is it possible to set these divs inside the container as rows/columns given by the user?

Note: As you can see, I am only using JavaScript and I would like to keep it, so please avoid answers with plugins/libraries/etc.

Upvotes: 3

Views: 1287

Answers (1)

Ortomala Lokni
Ortomala Lokni

Reputation: 62486

If you have N columns, one solution is to set the flex-basis property to a percentage of 100/N.

You can set it in javascript without libraries (as required) with:

div.style['flex-basis'] = 100/columns + '%';

Keeping the same settings as yours, you just have to add the previous line in the script like this:

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

var rows = prompt("How much lines do you want?");
var columns = prompt("And how much columns do you want?");

for(var i = 0; i < rows; i++){
   for(var j = 0; j < columns; j++){
      var div = document.createElement("div");
      div.classList.add("square");
      div.innerHTML="<p>" + i + "</p>";
      div.style['flex-basis'] = 100/columns + '%';
      container.appendChild(div);
   }
}

You can test it with the codepen : http://codepen.io/anon/pen/wGYKdY

Upvotes: 1

Related Questions