PiotrS PiotrS - 1 month ago 7
CSS Question

Dynamically add new div in grid

I have little problem, because I would like dynamically add (create) new div (cell of grid) click on button. This is simple, but trouble starts when I want this divs add three in line and add next row below (again three columns) and always new div will be add as first. Summary I would like dynamically create grid with three columns and infinity rows, and new div will be always first.

Thank you for your time and help :)

enter image description here

Answer

One approach is like this. You will use jQuery and append()

$('button').on('click', function(){
  $('#container').append($('<div class="item">'));
});
div.item{
  width: 30%;
  height: 50px;
  background: red;
  margin: 10px;
  float: left;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add div</button>
<div id='container'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>