Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "object-fit: contain" and "max-width: 100%;max-height:100%"?

Tags:

html

css

I was using "object-fit: contain" to scale an Image when I realised that it doesn't work in Internet Explorer / Edge. So I switched to "max-width: 100%;max-height: 100%;" and I was wondering where the difference is?

Maybe this is a stupid question, but I am a little confused.

like image 375
Britzsquad Avatar asked Oct 13 '25 07:10

Britzsquad


2 Answers

max-width and max-height property stop your image to go outside of container If you apply both property max-width:100% and max-height:100% then image will show in without stretching and within the container.

object-fit:contain :-

With object-fit contain you have to define your image height width otherwise it will go outside of container.

Using the object-fit property, you can fit the contents of an image into the dimensions you specify in your style sheet. The contain value tells the image to shrink or enlarge itself until it fits in the box while maintaining its aspect-ratio.

.first-item {
  height: 200px;
  width: 200px;
  margin-bottom: 10px;
}

.second-item {
  height: 200px;
  width: 200px;
  margin-bottom: 10px;
}

.first-item img {
  max-height: 100%;
  max-width: 100%;
}

.second-item img {
  object-fit: contain;
}
<div class="first-item">
  <img src="http://perform-ers.com/images/channel/logo/8f4beb43c0b80dd46228cb87364f4196.jpg" class="grid-img">
</div>
<div class="second-item">
  <img src="http://perform-ers.com/images/channel/logo/8f4beb43c0b80dd46228cb87364f4196.jpg" class="grid-img">
</div>
like image 170
kulbhushan charaya Avatar answered Oct 14 '25 21:10

kulbhushan charaya


It behaves similarly as background images:

contain should fit the image into the container so that the whole image will be visible and that it keeps its original proportion between width and height. Depending on the proportions of the container this can result in 100% width or 100% height, with the other parameter being set to auto.

width: 100%; height: 100% will in most cases distort the image: It will show the whole image (without cutting off anything), but it will stretch both parameters independently. Think of a 200x200px image that is put into a 400x600 container: The width will be strechted to twice the original, while the height will be stretched to three times the orignal height - this will result in an ugly distortion.

If object-fit: contain is applied to the same example (instead of width: 100%; height: 100%), the new img width will be 400px (= doubled), and the height will also be 400px, since the proportion is kept, resulting in some empty space, but also in a not distorted image.

like image 23
Johannes Avatar answered Oct 14 '25 21:10

Johannes