Adjust the image to fit and maintain aspect ratio

I want the image to fill 100% of its container width, and I want it to have a max-heigth property, and all this preserves the aspect ratio, but allows to lose any part of the image.

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

I know that this can be done using the background-size property, but I want to do this for the inline <img> .

Any idea how I can achieve this with CSS? or javascript?

+7
source share
1 answer

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

CSS3 object-fit / object-position Method for determining how an object (image or video) should fit inside its box. object options include β€œcontain” (suitable for aspect ratio), β€œfill” (stretch the object to fill) and cover (overflow box but maintain the ratio), where the object position allows the object to be moved as a background image.

JSFIDDLE DEMO

 .container { width: 200px; /*any size*/ height: 200px; /*any size*/ } .object-fit-cover { width: 100%; height: 100%; object-fit: cover; /*magic*/ } 
 <div class="container"> <img class="object-fit-cover" src="https://i.stack.imgur.com/UJ3pb.jpg"> </div> 

Additional Information:

+31
source

Source: https://habr.com/ru/post/1240307/


All Articles