OL Learn

Dynamic Image - fit to width or fit to height based on image dimensions

Approx. 75 logos with different sizes and shapes.
Have a location defined by a DIV to constrain the image.
With any specific logo one of the following will work, but need to determine which one.
Not sure how to write the CSS to chose which scenario is best.

style="max-width: 100%; height: auto;
style="max-height: 100%; width: auto;

Well first, how would you decide, as a human, which one would need to be used?

Then we can express this into code :wink:

Maintaining the aspect ratio, I’m thinking something like this.

Collecting the image width and height.

Max-Height
Calculating what the resulting image width would be if the image height was set to max-height

Max-Width
Calculating what the resulting image height would be if the image width was set to max-width

Decision
If the resulting image width exceeds the threshold then use the Max-Width.
If the resulting image height exceeds the threshold then use the Max-Height.
If neither the resulting image width or height the exceed thresholds then use the one that produces the larger resulting image.

I am no expert but if you set the <img> tag to:
max-width: 100%;
max-height: 100%;

Than it should rely on the <div> for the size of the image
Can you try it?

Got the idea from https://stackoverflow.com/questions/3029422/how-do-i-auto-resize-an-image-to-fit-a-div-container

which shows an example http://jsfiddle.net/xwrvxser/1/

1 Like

Alternatively set the image as background image for the div element and set the background-size property to “contain”. This scales the image as large as possible within its container without cropping or stretching the image.

2 Likes