How do you auto-resize a large image so that it will fit into a smaller width div container whilst maintaining it's width:height ratio?
Example: stackoverflow.com - when an image is inserted onto the editor panel and the image is too large to fit onto the page, the image is automatically resized.
Here is a solution that will both vertically and horizontally align your img within a div without any stretching even if the image supplied is too small or too big to fit in the div. The html:
The CSS:
The JQuery:
I hope this helps you guys out
Check out my solution: http://codepen.io/petethepig/pen/dvFsA
It's written in pure CSS, without any JS code. It can handle images of any size and any orientation.
Given such HTML:
CSS code would be:
Simplest way to do this is
by using object-fit
If your using bootstrap just add the img-responsive class and changed to
A simple solution is to use flex-box. Define the container's CSS to:
Adjust the contained image width to 100% and you should get a nice centered image in the container with the dimensions preserved. Cheers.
Do not apply an explicit width or height to the image tag. Instead, give it:
Also,
height: auto;
if you want to specify a width only.Example: http://jsfiddle.net/xwrvxser/1/
I have much better solution without need of any JS. It is fully responsive and I use it a lot. You often need to fit image of any aspect ratio to container element with specified aspect ratio. And having whole this thing fully responsive is a must.
You can set max-width and max height independently, image will respect the smallest one (depending on the values and aspect ratio of the image). You can also set image to be aligned as you want (eg. for product picture on infinite white background you can position it to center bottom easily)