Sebastian Hernandez
Sebastian Hernandez

Reputation: 2376

Force an image to fit and keep aspect ratio

I want an image to fill the 100% of its container's width, and I want it to have a max-heigth property set to it, all this keeping the aspect ratio but allowing to lose any part of the image.

img {
   max-height:200px;
   width:100%;
}

I know a similar thing can be done with background-size property but i want to make this to an inline <img> tag.

Any idea of how could i achieve this using CSS? or javascript?

Upvotes: 32

Views: 81230

Answers (2)

Stickers
Stickers

Reputation: 78756

You can try CSS3 object-fit, and see browser support tables.

CSS3 object-fit/object-position Method of specifying how an object (image or video) should fit inside its box. object-fit options include "contain" (fit according to aspect ratio), "fill" (stretches object to fill) and "cover" (overflows box but maintains ratio), where object-position allows the object to be repositioned like background-image does.

JSFIDDLE DEMO

.container-1 {
  width: 150px; /*any size*/
  height: 150px; /*any size*/
  border: 1px solid red;
}

.container-2 {
  width: 300px; /*any size*/
  height: 150px; /*any size*/
  border: 1px solid red;
}

.object-fit-cover {
  width: 100%;
  height: 100%;
  object-fit: cover; /*magic*/
}
<div class="container-1">
  <img class="object-fit-cover" src="https://i.sstatic.net/UJ3pb.jpg">
</div>

<br>

<div class="container-2">
  <img class="object-fit-cover" src="https://i.sstatic.net/UJ3pb.jpg">
</div>


Related Info:

Upvotes: 104

Sandeep K Nair
Sandeep K Nair

Reputation: 2932

You can achieve this using css flex properties. Please see the code below

.img-container {
  width: 150px;
  height: 150px;
  border: 2px solid red;
  justify-content: center;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  
}
.img-container .img-to-fit {
  flex: 1;
  height: 100%;
}
<div class="img-container">
  <img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />
</div>

Upvotes: 0

Related Questions