Geordie Geordie - 1 year ago 72
CSS Question

Scale image inside div up AND/OR down to fit largest side of image with CSS

I've looked through A LOT of Q&A here on the topic but can't find a definitive answer if one exists.

I have a div of dynamic width and height and want to fit any sized image inside of it and keep the aspect ratio. This could be scaling the image up or down:

Image scaling scenarios

I've tried every combo of width, height, max-width, max-height, Object-fit etc I can think of with no luck, there's always at least one case that fails. Most solutions I've seen involve some hard coded max-width or height values. Is it possible to get ALL above cases working only with CSS and a dynamically sized div container?

PS my target browser is Edge if that makes a difference.


Answer Source

Here's one way to do it.

Apply the image as an css background using background: url(path/to/image) and then using the background-size attribute to set the scaling to contain, background-size: contain (see fiddle,