Search code examples
htmlcsscontainers

CSS fit image to the container depending on the height or width


I have a container that has size, say 600 for width and 400 for height. Also I have 2 images one has size 600(width) * 1 and one has dimension 1 * 400(height). Is there a way that I fit the first image to the container using width or max-width and the second one using height or max-height? Thanks.


Solution

  • The img tag is the only element that can auto scale to match the image size.

    Depending on your scenario you might be able to use a container width a fixed width & height and use background-size: contain.

    Otherwise you have to use javascript and do the math yourself.

    Is there a way that I fit the first image to the container using width or max-width and the second one using height or max-height?

    In short: no.

    Here's an example with the img tag: http://jsfiddle.net/sn3uu0uw/2/