Bootstrap 4卡片组:每行卡片数不足时固定卡片宽度
Hey, I get it—you've got a responsive card layout using Bootstrap 4's card-deck that works pretty well for the most part: it keeps the right number of cards per row at different screen sizes, and all cards stay the same height. But that annoying problem where the last row's lone card stretches to fill the whole row instead of matching the width of the cards above and aligning left? I've been there too.
The Root of the Problem
Your current approach uses media queries and <span> separators to control how many cards fit per row, but card-deck's default behavior is to make all cards in the deck share the container width equally. So when the last row doesn't have enough cards to fill the row, that remaining card gets stretched to take up the extra space.
The Simple Fix: Set a Global max-width on Cards
This issue can be solved by defining breakpoint-specific max-width values for your cards. Plus, adding an ID to your target card-deck ensures your styles only apply to this specific set of cards, not every card on your site.
Step-by-Step Implementation:
- First, add a unique ID to your
card-deckto scope the styles:
<div id="custom-card-grid" class="card-deck"> <!-- Your card elements go here --> </div>
- Then, add these media queries to set the correct
max-widthfor each screen size:
/* Large screens (992px - 1199px): Max 4 cards per row */ @media (min-width: 992px) and (max-width: 1199px) { #custom-card-grid .card { max-width: calc(25% - 15px); /* 25% for 4 equal cards, minus gutter spacing */ } } /* Medium screens (768px - 991px): Max 3 cards per row */ @media (min-width: 768px) and (max-width: 991px) { #custom-card-grid .card { max-width: calc(33.333% - 15px); /* 33.333% for 3 equal cards */ } } /* Small screens (576px - 767px): Max 2 cards per row */ @media (min-width: 576px) and (max-width: 767px) { #custom-card-grid .card { max-width: calc(50% - 15px); /* 50% for 2 equal cards */ } } /* Extra small screens (<576px): 1 card per row */ @media (max-width: 575px) { #custom-card-grid .card { max-width: 100%; } }
Why This Works
By setting a max-width for each breakpoint, you're telling each card never to exceed the width it would have if the row was full. Even when the last row has fewer cards, they'll stay at that fixed width instead of stretching to fill the container—perfectly aligning left with the cards above.
Also, you can go ahead and remove those <span> separators you were using before; this solution doesn't need them to control row breaks, keeping your HTML cleaner.
内容的提问来源于stack exchange,提问作者S.Stevens

