How to resize image to container size?

4

I have a div with 1184x308px and want to be placed inside images that are dynamic.

Because images can be loaded with any dimension, how can I adjust the dimensions of div ?

    
asked by anonymous 03.03.2015 / 11:02

2 answers

7

If the image is smaller than the div dimension, the max-width and max-height approach will not work, so it's best to put width: 100%; and play with height to be able to hit the image. Placing height: auto; will make the image increase in height proportionally. If you force it to height: 100%; , the image will be disproportionate, but occupying the entire height of the div. Even so, the max-width/height approach is also well indicated.

Try to crop images always in the ratio you need or set width: auto and height: 100% to make the image always 100% height and width will always extrapolate the div. So, put a overflow: hidden in the div, so it does not show the part of the image that will overflow the width.

div {
    width: 500px;
    height: 200px;
    overflow: hidden; /* Faz o div não aumentar a altura por causa da imagem */
}

img {
    border: 1px solid red;
    width: 100%;
}

link

    
28.04.2015 / 12:53
2

You can do this as follows:

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

.minha-div {
    height: 50px;
    width: 50px;
}
A minha div
<div class="minha-div">
    <img src="http://www.deshow.net/d/file/animal/2009-07/cute-kitten-631-2.jpg">
</div>

The trick is to put the maximum dimensions ( max-width , max-height ) of the image to 100% which causes them to fill div . If the images are smaller, they are not affected.

    
03.03.2015 / 11:34