sandboxj
sandboxj

Reputation: 1254

How make Bootstrap 4 card decks same width each row?

I am displaying 4 cards each row using a card deck:

<div class="row">
  <div class="card-deck">
    <!-- 4 of these -->
    <div class="card">
      <img class="card-img-top img-adjusted" >
       <div class="card-body">...</div>
    </div>
  </div>
</div>
<div class="row">
  <div class="card-deck">
    <!-- 4 of these -->
    <div class="card">
      <img class="card-img-top img-adjusted" >
       <div class="card-body">...</div>
    </div>
  </div>
</div>
...

The cards within each deck are the same width, but the decks are not, i.e. the deck of the 2nd row is wider than the deck of the 1st row. How do I get the decks to be of the same width?

I have tried setting .card-decks{width: 100%;}, which works for full rows, but distorts cards of rows that have just 1-2 cards.

Additional CSS: My images are of different sizes, that's why I added the following CSS to make them the same. No other CSS should affect the cards:

.img-adjusted{
position: relative;
float: left;
background-position: 50% 50%;
background-repeat:   no-repeat;
background-size:     cover;
}

Also, I want to keep the style responsive, so would like to avoid hardcoding pixel set pixel widths.

Upvotes: 6

Views: 27828

Answers (1)

Carol Skelly
Carol Skelly

Reputation: 362810

Don't put .card-deck in a .row. Only .col- columns should be placed in rows...

content must be placed within columns and only columns may be immediate children of rows.

You should use...

<div class="row">
 <div class="col-12">
  <div class="card-deck">
    <!-- 4 of these -->
    <div class="card">
      <img class="card-img-top img-adjusted" >
       <div class="card-body">...</div>
    </div>
  </div>
 </div>
</div>

The 2nd part of the question...

When using card-deck (and card-group), cards will always fill the width of the next visual row. If you have less than 4 cards in each row, the remaining cards will fill the width across. To workaround this, set a max-width for each card..

.card-deck .card {
    max-width: calc(25% - 30px);
}

https://www.codeply.com/go/ygvZvjsELs

Alternatively, You can use the grid columns to wrap the cards. This is explained here: Bootstrap 4 card-deck with number of columns based on viewport

Upvotes: 18

Related Questions