How to resize and crop an image with CSS, inside a Bootstrap Card?

1.1k Views Asked by At

Following problem: I have some Bootstrap card elements with pictures, and some pictures have different sizes/ratios, like the one in the middle (see attached screenshot). Therefore my card elements are not in one row. That's not very nice.

Now I would like to resize these images to the height of the others, and crop the overflow. How do i do that? Heres my code snippet of one card...

<div id="cities">
  <div class="city">
    <div class="card">
      <div class="city-img-container">
        <img class="card-img-top city-img" src="..." alt="New York City">
      </div>
      <div class="card-body">
        <h5 class="card-title"><b>Name: </b>New York City</h5>
        <p class="card-text"><b>Land: </b>USA<br>
            <b>Spitzname: </b>The Big Apple</p>
        <div class="city-bottom-content">
            <a href="#/city?id=35" class="btn btn-primary" data-id="35">
              <i class="bi bi-arrow-right"></i>
            </a>
            <button data-id="35" class="is-favorite">
              <i class="bi bi-heart-fill"></i> 
            </button>
        </div>
    </div>
  </div>

  <div class="city">
    ...
  </div>
</div>

PS: The card elements inside of #cities are arranged with grid and grid-template-columns.

Thank uuu! :)

screenshot

2

There are 2 best solutions below

2
On BEST ANSWER

You can make all of the images the same height (and width) by using object-fit.

.card-img-top {
    width: 100%;
    height: 15vw;
    object-fit: cover;
}

In the example above, the height of all images will be 15% of the viewport width. This could be whatever you please...500px, 10vh, etc.

The object-fit: cover;, will likely hide parts of images - but perhaps you could implement a means of viewing them in full-size when clicked on? Either way, it's a nice approach to keep the cards fairly uniform.

Note that you are just making some adjustments to the existing Bootstrap class .card-img-top. You could include this CSS on your HTML file, in your CSS file, or update the class in your Bootstrap file if you downloaded it.

0
On

Give a fixed height to image tag so small images will automatically expand.

<img class="card-img-top city-img" height="200px" src="..." alt="New York City">