Geordie
Geordie

Reputation: 2184

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.

THANKS!!

Upvotes: 2

Views: 3255

Answers (2)

Mathias W
Mathias W

Reputation: 1521

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, https://jsfiddle.net/mghgsk5e/).

Upvotes: 0

Le-roy Staines
Le-roy Staines

Reputation: 2057

For all modern browsers except Edge, and all versions of Internet Explorer, you can use the CSS property object-fit.

Example: https://jsfiddle.net/09cpe9e0/1/

I would be inclined to implement a javascript solution for Internet Explorer and Edge that can be removed at a later date, leaving only the CSS version when it is safe to do so.

Upvotes: 1

Related Questions