问题
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:
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!!
回答1:
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/).
回答2:
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.
来源:https://stackoverflow.com/questions/39279460/scale-image-inside-div-up-and-or-down-to-fit-largest-side-of-image-with-css