Ben Botvinick
Ben Botvinick

Reputation: 3285

Make card image fill height and width in Bootstrap 4

How do I make images take up the entire width of a card-img in a Bootstrap 4 card? What I want to do is set the height of the card-img and have the width be automatically filled and the image vertically centered in the card. I need to do this because I have multiple cards with different images of different sizes in a row. Right now, my code looks like this:

<div class="row">
  <div class="col-6">
    <div class="card h-100 border-0 shadow">
      <div class="card-img-top overflow-hidden">
        <img src="..." alt="" class="img-fluid" />
      </div>
      <div class="card-body">
        <p>Card content goes here</p>
      </div>
    </div>
  </div>

  <div class="col-6">
    <div class="card h-100 border-0 shadow">
      <div class="card-img-top overflow-hidden">
        <img src="..." alt="" class="img-fluid" />
      </div>
      <div class="card-body">
        <p>Card content goes here</p>
      </div>
    </div>
  </div>
</div>

So in this scenario, the two imgs are different sizes. I want the two cards to be the same height, and I want the images to fully take up the card-img whether they are longer than they are wide, or wider than they are long.

Upvotes: 2

Views: 5131

Answers (1)

Cue
Cue

Reputation: 2759

By far the simplest form of image equality in size is using aspect ratio's. Bootstrap has an embed utility that you can utilise for such a case. It's shipped with 16x9 and 4x3 aspect ratio but you can easily add your own.

In this demonstration I've provided two images, one landscape and the other portrait, both of which appear the same and fill the available aspect ratio.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div class="col-6">
      <div class="card h-100 border-0 shadow">
        <div class="card-img-top">
          <div class="embed-responsive embed-responsive-4by3">
            <div class="embed-responsive-item">
              <img src="https://placeimg.com/640/480/any" alt="" class="img-fluid w-100" />
            </div>
          </div>
        </div>
        <div class="card-body">
          <p>Card content goes here</p>
        </div>
      </div>
    </div>
    <div class="col-6">
      <div class="card h-100 border-0 shadow">
        <div class="card-img-top">
          <div class="embed-responsive embed-responsive-4by3">
            <div class="embed-responsive-item">
              <img src="https://placeimg.com/480/640/any" alt="" class="img-fluid w-100" />
            </div>
          </div>
        </div>
        <div class="card-body">
          <p>Card content goes here</p>
        </div>
      </div>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions