How to Maintain Aspect Ratio While Taking Up 100% of Container Width or Height, Whichever is Smaller

Good day everyone :wave: :smile:

Iโ€™m wondering how I can make an image (or any HTML/CSS object, really), which is centered in a div, maintain a 1:1 aspect ratio while taking up 100% of either the width or the height of the div, whichever is smaller.

That is to say, if the div is taller than it is wide, the image width should be 100% of the div width, and the image height should be equal to its width (the image remains square), and vice versa.

Thank you!

1 Like

You will need to write some JavaScript code to make this design happen I think.

Not sure I really understand the question. A 1/1 aspect ratio would imply the width and height are the same.

There are dynamic viewport units and you also have container queries.

1 Like

My bad; I might have worded that somewhat confusingly.

Imagine an image contained within a rectangular div.

The image is always a square (aspect ratio of 1/1), but the side length of that square is equal to the smaller dimension of the div containing the square image. If, for example, the div has a height of 100px and a width of 50px, then the image will have both a height and width of 50px (the complete width of the div), and will be centered vertically in the div, leaving 25px of empty space above it and another 25px of empty space below it.

If the div then changes size, keeping its width of 50px but changing its height to 25px, the image will now become a 25px by 25px square. It would be centered horizontally in the div, leaving 12.5px of empty space to its left and the same to its right.

1 Like

Youโ€™re probably right, unfortunately. Letโ€™s see if anyone else has any ideas though.

i came across an implementation that may help you use aspect-ratio for this:

1 Like