SurajS
SurajS

Reputation: 497

Setting image without cropping and stretching

I want to set image in img tag, without cropping it or stretching it. That is, the image ratio I have set is 1:1 but image may vary in aspect ratio, so I neither want to change the aspect ratio nor want to crop it vertically or horizontally. my images are changing dynamically.

I have checked multiple solutions for eg: This one which suggests either crop height or width. But I don't want both.

Currently I am at this: HTML:

<div id="container">
    <img id="imgHolder" />
</div>

and CSS

#container{
        height: 100px;
        width: 100px;
        background-color: yellow;
        overflow: hidden;
    }
    #imgHolder{
        height: 100%;
        /* OR width: 100%; */
    }

Help. I prefer CSS only.

Upvotes: 3

Views: 5892

Answers (2)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

you can just set both the max-width and the max-height of your images

#container img {
  max-width: 100%;
  max-height: 100%;
}

Doing so the image won't be stretched since your not changing its width or height: whatever is the image size, setting the above properties together ensures that the longest side is reduced to the maximum width (or height) of its parent div, while the other one can freely adapt itself, keeping the original image ratio.

Example http://codepen.io/anon/pen/qEjLZa


Example with centered images (both ver. and hor.): http://codepen.io/anon/pen/NPgege

Upvotes: 4

Justin Breiland
Justin Breiland

Reputation: 460

If you set a height and width on the parent container, it is hard to retain a perfect aspect ratio without stretching or cropping the image. If the image is the same size, 100px x 100px then you could use

CSS

#container{ position: relative; width: 100px; height: 100px; }

img{ 
  position:absolute;
  top:0px;
  bottom:0px;
  right:0px;
  left:0px;
  }

This will set the image to cover the parent container. You could also try

img {
  background: url( yourimage.png) cetner no-repeat;
  background-size: contain;
}

This will set the image to fill the larger of the dimensions to the parent container and will center it. The smaller dimension will not be covered, but it will retain is apsect ratio.

Upvotes: 0

Related Questions