How to resize image to container size?

Asked

Viewed 40,440 times

4

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

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

2 answers

7

If the image is smaller than the size of the div, the max-width and of max-height will not work, then it is better to put width: 100%; and play with the height to be able to hit image. Place height: auto; will make the image increase the height proportionally. If you force to height: 100%;, the image will be disproportionate, but occupying the entire height of the div. Even so, the approach of the max-width/height is quite indicated also.

Try to crop the images always in the proportion you need or define a 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 doesn’t show the part of the image that will overflow from 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%;
}

http://jsfiddle.net/80yw8h5b/

  • 1

    If you want you can create a snippet here on Stackoverflow even @Diegoeis: Further explanations - Of course, just suggestion :)

2

You can do it this way:

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) image to 100% what causes them to div. If images are smaller, they are not affected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.