1

I would like to display in a grid of 4 columns per row my images which are loaded dynamically by clicking on a button.

My problem is that I don't know in advance how many image the user wants to display so I cannot separate the view in "row" and place a "col-md-3" on each div in the row.

I thought by keep adding on the same div it will stack the image in row but it doesn't.

This is how it is displayed :

How it display it

How i wanted to be displayed :

How i want it

Can someone help me ? The code is here http://jsfiddle.net/htwist/LR78M/12/

<div class="container">
<div id="content-div" class="row">
    <div class="col-md-3">
        <img class="img-responsive" src="http://placehold.it/100x200&text=1rst" />
    </div>
    <div class="col-md-3">
        <img class="img-responsive" src="http://placehold.it/120x50&text=2nd" />
    </div>
    <div class="col-md-3">
        <img class="img-responsive" src="http://placehold.it/120x50&text=3rd" />
    </div>
    <div class="col-md-3">
        <img class="img-responsive" src="http://placehold.it/120x40&text=4th" />
    </div>
    <div class="col-md-3">
        <img class="img-responsive" src="http://placehold.it/120x120&text=5th" />
    </div>
    <div class="col-md-3">
        <img class="img-responsive" src="http://placehold.it/60&text=6th" />
    </div>
    <div class="col-md-3">
        <img class="img-responsive" src="http://placehold.it/60&text=7th" />
    </div>
</div>
<div class="row">
    <div class="col-md-12">
        <button class="btn">Add more img</button>
        <input type="text" id="width" />
        <input type="text" id="height" />
    </div>
</div>
</div>

$(function () {
$('.btn').click(function () {
    var size = $('#width').val().length > 0 ? $('#width').val() : '60' + 'x' + $('#height').val().length > 0 ? $('#height').val() : '60',
        html = '<div class="col-md-3"><img class="img-responsive" src="http://placehold.it/' + size + '" /></div>';
    $('#content-div div:last').after(html);
});
});
K. L.
  • 654
  • 2
  • 10
  • 21

1 Answers1

2

A row can have 12 columns, once you have assigned all the 12 with (col-md-3 * 4), you need to clear the floats so that the next columns do not follow them, so all you need is:

<div style="clear:both;"></div> 

after the first 4 divs.

Fiddle

Detail on why you need to clear floats explained here by Mr. Alien.

Community
  • 1
  • 1
AyB
  • 11,609
  • 4
  • 32
  • 47