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%
and
height: 100%
and the same for
max-width
and
max-height
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?

Basically:
width:100%
unless that makes
height
greater than 100%, in which case I want to use
height:100%
.

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