css div size and img size

You must have encountered such case that an image is larger than its container div and can not be restricted in the div area.

<div><img src="image.png" alt="" /></div>

In the example above, if the size of image.png is larger than 56px*56px, it extends out of the containing div. How to scale down the image to fit in the div? One method is using width/height attributes of img or using a style to specify the width and height of the image so that it is equal or smaller than div, e.g.,

<div><img src="image.png" alt="" width="56px" height="56px/" /></div>

Now the image occupies the area specified by the width and height attributes regardless of the real size of the image and the size of the containing div. So if the ratio of the specified width and height is not equal to the ratio of the original width and height of the image, the image appears warped. You can use the max-width/max-height style attributes of img to fit the image into the div, e.g.,

<div><img style="max-width: 100%;" src="image.png" alt="" /></div>

In this case, the aspect ratio keeps as the original image, but the width cannot be larger than the width of the container or the original width of the image, which is smaller. Likewise, for

<div><img style="max-height: 100%;" src="image.png" alt="" /></div>

the height of the final image is the height of the div or the height of the original image,which is smaller. if both max-height:100% and max-width:100% are used, the final image will be restricted within the div although there may be some extra area in the div if the aspect ratio of the div is not the same as the original image. If you do not want the extra space you can use:

<div><img style="height: 100%; width: 100%;" src="image.png" alt="" /></div>

which makes the div full of the image(of course the image may be warped if the original aspect ratio is not the same as that of the div)

Leave a Reply