Search code examples
phphtmlcsstwitter-bootstrap-3grid-layout

Tile Thumbnails in a Grid


I want to tile thumbnails into 3 columns using bootstrap's grid classes like this (this entry only has 3 images): example

The 4th image would go to the next row <div class="row"></div> within a <div class="col-sm-4"></div>, 5th and 6th images in the same row but separate <div class="col-sm-4"></div>. Then the 7th image goes to the 3rd row etc...

The details of the images including urls are taken from DB using php.

<div class="panel-body">
    <?php foreach($screenshots as $key=>$screenshot): ?>
    <div class="col-sm-4">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title"><?=$screenshot["ss_name"]?></h3>
            </div>
            <div class="panel-body">
                <img class="img-rounded" style="display: block; text-align:center;" src="<?=UPLOADS_FOLDER.$screenshot['ss_url']?>" alt="<?=$screenshot['ss_name']?>">
                <p><?=$screenshot["ss_description"]?></p>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

I've managed to figure out the algorithim:

<?php
$total_entries = count($screenshots);
$total_cols = 3;
$total_rows = ceil($total_entries / $total_cols);

for($col = 0; $col < $total_cols; ++$col):
?>
    <div class="row" style="margin: 1% 0.5%;">
    <?php for($row = 0; $row < $total_rows; ++$row): ?>
        <div class="col-sm-4">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Panel Title</h3>
                </div>
                <div class="panel-body">
                    row: <?=$row?> | col: <?=$col?>
                </div>
            </div>
        </div>
    <?php endfor; ?>
    </div>
<?php endfor; ?>

Generated Grid with Panels

But I'm stuck trying to figure out how to find of the index of the screenshot to show.


Solution

  • You have row and column mixed up in the output above. Once that is fixed, if you need an integer index you should be able to calculate it from the row and column values. For a zero based array of images, something like (row*3)+column

    That said, in Bootstrap, you should not need to create the individual rows in the way you have. If you put all the col-sm-3 divs one after the other, without breaking out new rows, this will sort itself out anyway. Doing it this way, you can use col-Xxx to specify different numbers of columns for different screen widths without changing your code.