htmlcss

HTML CSS Fit image in fixed size


I know this topic has been featured a couple times but none of the answers given to those questions fixed my problem. That's why I'm asking it here. I have a site where I have a standard Bootstrap card with an Image above it, But It looks like this enter image description here

How can I make the images so they automatically fit in the middle and don't look like they're stretched out?

This is my HTML code (There is no CSS attached, Its standard bootstrap)

<div class="row mt-4">
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-image">
                        <img class="card-img-top" src="images/example.png">
                    </div>

                    <div class="card-header">
                        <h6 class="m-0">Some text</h6>
                    </div>
                    <div class="card-body" style="height: 130px">

                        <p class="m-0">Some text</p>

                    </div>
                    <div class="card-footer">

                        Footer
                    </div>
                </div>
            </div>
</div>

Solution

  • The best thing to do is to use the image as a background in conjunction with background cover. This will allow the photo to grow and resize without looking wonky.

    .card-header {
      height: 200px;
      background-image: url('http://www.fillmurray.com/g/500/200');
      background-size: cover;
      background-position: center center;
    }
    
    .sr-only {
      position: absolute;
      width: 1px;
      height: 1px;
      padding: 0;
      margin: -1px;
      overflow: hidden;
      clip: rect(0, 0, 0, 0);
      white-space: nowrap;
      border-width: 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
    <div class="row mt-4">
      <div class="col-md-4">
        <div class="card mb-4">
          <div class="card-image">
            <img class="card-img-top sr-only" src="images/example.png">
          </div>
          <div class="card-header">
            <h6 class="m-0">Some text</h6>
          </div>
          <div class="card-body" style="height: 130px">
            <p class="m-0">Some text</p>
          </div>
          <div class="card-footer">
            Footer
          </div>
        </div>
      </div>
    </div>