如何合理循环渲染Bootstrap列?解决连续full类型布局留白问题
Hey there! Let's sort out that frustrating blank space you're getting when multiple full-type events show up in a row. The core issue with your current code is that each event is wrapped in its own .row—so every full event takes up an entire row even though there's room for a half event to fill the leftover col-lg-4 space. Here's a practical solution to make your layout fit perfectly:
The Approach
We'll track how many columns we've used in the current row and group events together until we hit Bootstrap's 12-column limit. This way, a full event (8 columns) will automatically pair with a half event (4 columns) in the same row, and consecutive fulls will only start new rows when there's no half event left to fill the gap.
Updated Laravel Blade Code
<?php // Track columns used in the current row (Bootstrap uses 12-column grid) $currentRowColumnCount = 0; // Store events that belong to the current row $currentRowEvents = []; ?> @foreach($newEvent as $event) <?php // Define column count and classes based on event type $columnCount = $event->type === 'half' ? 4 : 8; $columnClasses = $event->type === 'half' ? 'col-lg-4 col-md-6' : 'col-lg-8 col-md-12'; // Check if adding this event would exceed 12 columns if ($currentRowColumnCount + $columnCount > 12) { // Render the completed row first ?> <div class="row"> @foreach($currentRowEvents as $rowEvent) <div class="{{ $rowEvent['classes'] }}"> <div class="card"> <!-- Your existing image and event info goes here --> <!-- Example: {{ $rowEvent['data']->title }} --> </div> </div> @endforeach </div> <?php // Reset for a new row with the current event $currentRowColumnCount = $columnCount; $currentRowEvents = [ ['data' => $event, 'classes' => $columnClasses] ]; } else { // Add the current event to the existing row $currentRowColumnCount += $columnCount; $currentRowEvents[] = [ 'data' => $event, 'classes' => $columnClasses ]; } ?> @endforeach <!-- Don't forget to render the last incomplete row --> @if(!empty($currentRowEvents)) <div class="row"> @foreach($currentRowEvents as $rowEvent) <div class="{{ $rowEvent['classes'] }}"> <div class="card"> <!-- Your existing image and event info goes here --> <!-- Example: {{ $rowEvent['data']->title }} --> </div> </div> @endforeach </div> @endif
How It Works
- Column Tracking:
$currentRowColumnCountkeeps tabs on how much of the 12-column grid we've used in the current row. - Dynamic Grouping: When adding a new event would push us over 12 columns, we render the current row and start fresh. Otherwise, we keep adding events to the row.
- Responsive Compatibility: Your
col-md-6andcol-md-12classes still work as intended—this logic focuses on fixing the lg-screen spacing while preserving mobile/tablet layout.
This method ensures no awkward white space remains, and your events will fill the row as efficiently as possible!
内容的提问来源于stack exchange,提问作者ram ram

