Search code examples
htmlcssimageweb-frontend

How to make image fit to its div CSS


Let's suppose I have the following code:

img {
  max-widht: 100%;
  max-height: 100%;
}
<div width="500" height="500">
  <img src="https://placehold.it/250x150">
</div>

This works fine for all images if with width or height higher than 500px. But with smaller images, the image will not cover the div. Is there a CSS way to force the image to be a least width: 100% or height: 100% regardless its original size ?

EDIT : This solution by disinfor worked for me.

img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}

Solution

  • Do this:

    img {
        width: 100%;
        height: auto;
    }
    

    The reason smaller images (in your case, smaller than 500px wide) don't fill the whole space, is because max-width means "max width of the actual image." So if you use width: 100% instead, the image will fill the space of its container.

    Using height: auto will ensure the image doesn't get stretched/distort vertically.

    Proof of concept:

    .normal, .land, .port, .fit {
      height: 200px;
      width: 200px;
    }
    
    img {
      width: 100%;
      height: auto;
    }
    
    div.land img,
    div.port img {
      width: 100%;
      height: 100%;
    }
    
    div.fit img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    <div class="fit">
      <img src="https://placehold.it/500x750">
    </div>
    
    <div class="fit">
      <img src="https://placehold.it/50x100">
    </div>
    
    <div class="normal">
      <img src="https://placehold.it/75x10">
    </div>
    
    <div class="normal">
      <img src="https://placehold.it/10x75">
    </div>
    
    <div class="land">
      <img src="https://placehold.it/75x10">
    </div>
    
    <div class="port">
      <img src="https://placehold.it/10x75">
    </div>