简体   繁体   中英

Bootstrap 4 Card Deck Fixed Card Width (when less than specified amount of cards per row)

I have a deck of x amount of cards on my website, so far, I am pretty pleased with how they behave responsively. They never exceed the set amount, n, per row for a given resolution, they remain the same height etc. The only issue, however, is that If I have a row of 2, with 2 below, then an extra 1 in a third row, that final card will expand to fill the width of 2 cards instead of staying the correct size, and staying to the left.

I am using a system similar to below to set how many cards are allowed per row, for a set resolution:

@media (min-width:992px) and (max-width: 1199px) {
   .card-deck span:nth-of-type(4n) {
      display: block;
      width: 100%;
    }

}
@media (min-width:768px) and (max-width: 991px) {
    .card-deck span:nth-of-type(3n) {
      display: block;
      width: 100%;
    }
}
@media (min-width: 576px) and (max-width: 767px) {
    .card-deck span:nth-of-type(2n) {
      display: block;
      width: 100%;
    }
}

And then each card is defined in HTML as:

        <div class="card-deck">
        <div class="card mb-4" data-clickable="true" data-href="#">
            <img class="card-img-top" src="https://via.placeholder.com/700x400" alt="Card image cap">
            <div class="card-body">
              <h5 class="card-title">Test Card</h5>
            </div>
            <div class="card-footer">
              <small class="text-muted">More Info Here</small>
            </div>
        </div>
        <span></span>

Each card is separated by a span tag, I can't remember why.

Here is a codepen: https://www.codeply.com/p/A2JgtdhP1Y (press tablet view, then change the width whilst watching the bottom card/s)

As you can see at certain resolutions the cards on the bottom row, if they are less than the maximum amount of cards allowed in that row will try to fill the gap by expanding width ways, I would like to stop this and have them aligned to the left with the same width as the other cards above.

EDIT: For anyone else who has this issue, setting the global max-width for cards works. You have to try a few different widths for all of your media queries so the bottom one lines up, I also used a html id for my card deck so this css would only apply to those specific cards and would not apply site wide.

You need to define max-width at global level. You can refer to bootstrap documentation.

https://getbootstrap.com/docs/4.0/components/card/

or you can refer this previous post.

Previously discussed: Bootstrap 4 card-deck with number of columns based on viewport

.card {
    max-width: 13rem;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM