Jake P Jake P - 3 years ago 94
CSS Question

Auto-Resize Image to fill div

I have an image inside of a div which I need to have as large as possible. I have tried using

width: 100%
height: 100%
and the same for
but that has not worked. The reason these are not working is because my images are various sizes, some tall and some wide. Is there a way to have the image resize so that it will be as wide as possible without having height extend the div?

unless that makes
greater than 100%, in which case I want to use

Answer Source

One of the more elegant solutions is to set the size of the div, then set its background to url(foo) cover. This chops off the edges if need be. Using contain instead of cover does the same, but without chopping off the edges.

Edit: Per comments, I suggested using object-fit: contain. No need to downvote over my suggestion to use a background image.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download