Loop row in bootstrap every 3 columns

Loop row in bootstrap every 3 columns

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Looping Bootstrap Grids Without Explicit Row Wrappers

When rendering a grid of thumbnails in a server-side template like Blade, the instinctive approach is often to let the container handle the layout automatically. You might assume that if you set col-md-3 on each item and ensure the total width doesn't exceed 100%, Bootstrap will magically wrap them. However, Bootstrap's grid system operates on a strict 12-column basis per row, and it does not interpret "stacking" as a signal to create a new DOM element for the next line unless you explicitly define that boundary.

The code snippet provided demonstrates the root cause of the stacking issue:

foreach ($rows as $row){
    ?>  
        <div class="col-md-3">
            <div class="thumbnail">
                <img src="user_file/<?php echo $row->foto; ?>">
            </div>
        </div>
    <?php
}

In this implementation, every iteration generates a div with the class col-md-3. This element is intended to occupy three of the twelve available columns in a row. While the math suggests that four items would fit perfectly in a single row ($4 \times 3 = 12$), the browser renders these elements sequentially within the same parent container. Without an explicit <div class="row"> wrapper, or a mechanism to close and reopen the row context, the browser treats them as siblings in a flat list. If the parent container lacks overflow: hidden or specific flex properties, the items may visually wrap, but they remain part of a single logical grid row. More critically, if you rely on CSS classes that enforce strict row behavior (like those in older Bootstrap versions), the items will stack vertically within the same visual block rather than creating distinct horizontal lines.

To achieve the layout where thumbnails reset to the left after every three items, you must introduce a conditional wrapper. The standard pattern involves checking the loop counter and inserting a closing </div> tag for the current row whenever the count reaches a multiple of your desired column span.

Here is how to implement that logic in Blade:

$count = 0;
foreach ($rows as $row){
    // Increment the counter
    $count++;

    // Insert a closing row div if we hit the end of a 3-column set
    if ($count % 3 == 0) {
        echo '</div>'; 
    }

    ?>  
    <div class="col-md-3">
        <div class="thumbnail">
            <img src="user_file/<?php echo $row->foto; ?>">
        </div>
    </div>
    <?php
}
// Don't forget to close the final row if the dataset isn't a perfect multiple of 3
if ($count % 3 != 0) {
    echo '</div>';
}

This approach relies on integer division to determine when the current logical row has been filled. When $count is divisible by 3, we know we have reached the right edge of a grid row and must close the wrapper before rendering the next set of columns. This ensures that any subsequent items start a fresh <div class="row"> (assuming your outer container wraps these in rows, or if you are manually wrapping each group).

However, relying on modulo arithmetic inside a loop can introduce fragility. If your data source changes size—say, the last page of an album contains only one photo—the logic must handle that incomplete final row gracefully. The conditional check at the end of the loop handles this edge case, ensuring the grid container doesn't remain unclosed, which could break layout in responsive designs.

A more robust alternative, often preferred in modern frameworks, is to use the array_chunk function. This separates the logic from the rendering entirely, making the code easier to read and debug. You can chunk the $rows array into groups of three and then iterate over those chunks:

$chunks = array_chunk($rows, 3);

foreach ($chunks as $chunk) {
    echo '<div class="row">';
    
    foreach ($chunk as $row) {
        ?>  
        <div class="col-md-3">
            <div class="thumbnail">
                <img src="user_file/<?php echo $row->foto; ?>">
            </div>
        </div>
        <?php
    }
    
    echo '</div>';
}

By offloading the counting logic to array_chunk, you eliminate the need for manual counters and modulo checks within the render loop. This method guarantees that every iteration of the outer loop represents exactly one complete row, provided the input array length is a multiple of three. If the final chunk has fewer than three items, it will still render as a valid partial row, which usually satisfies responsive design requirements without extra code.

For developers working with dynamic data where strict 3-column layouts are non-negotiable regardless of content count, this separation of concerns offers significant maintainability benefits. It avoids the common pitfall of leaving an open grid container at the bottom of a page, a scenario that can cause layout shifts on mobile devices where column spans change from col-md-3 to col-6 or col-12.

For further reading on handling complex grid layouts and responsive breakpoints in Laravel projects, refer to https://laravelcompany.com.

Our network