Search code examples
htmlcssbootstrap-4bootstrap-cards

Crop image in card


I've built this horizontal card with an image on the left, and I've specified a min height for the card which is important.

Currently the image fits in the card using width: 100% and height: 100%, but i want it to use the full height of the parent and then crop the width of it.

I am using Bootstrap 4

HTML

<div class="card mb-3 rounded shadow">
  <div class="row no-gutters">
    <div class="col-md-4">
      <img src="{{ course.media[0].fileName }}" class="card-image" alt="">
    </div>
    <div class="col-md-8">
      <div class="card-body">
        <span class="badge badge-pill badge-danger">{{ course.courseNumber }}</span>
        <h5 class="card-title">{{ course.name }}</h5>
        <p class="card-text">{{ course.description }}</p>
      </div>
    </div>
  </div>
</div>

CSS

$nav-red: #e51400;

.card {
    max-width: 540px;
    min-height: 200px;
}

.card-image {
    width: 100%;
    height: 100%;
}

.card-body span{
    background-color: $nav-red !important;
    float: right;
}

Solution

  • Although I am not sure about your goal, I think that css "object-fit" property is what are you looking for. I have forked simple project that based on your provided HTML and CSS + Angular: https://angular-bootstrap-4-sandbox-mc8neu.stackblitz.io

    Main important difference is that I've added "min-height" to a .card > .row element, to fix fitting problem.

    Final code looks like this:

    HTML

    <div class="card mb-3 rounded shadow">
      <div class="row no-gutters">
        <div class="col-md-4">
          <img src="{{ course.media[0].fileName }}" class="card-image img-fluid img-cover" alt="">
        </div>
        <div class="col-md-8">
          <div class="card-body">
            <span class="badge badge-pill badge-danger">{{ course.courseNumber }}</span>
            <h5 class="card-title">{{ course.name }}</h5>
            <p class="card-text">{{ course.description }}</p>
          </div>
        </div>
      </div>
    </div>
    

    SCSS

    .card {
        max-width: 540px;
        > .row {
            min-height: 200px;
        }
    }
    
    .card-image {
        width: 100%;
        height: 100%;
    }
    
    .card-body span{
        background-color: #e51400 !important;
        float: right;
    }
    
    .img-cover {
      object-fit: cover;
    }