Steve A Steve A - 2 years ago 67
HTML Question

Max-width on img prevents image from shrinking

When I add max-width to an image, it correctly prevents the image from getting wider than the specified size, however, it also prevents the image from shrinking when the browser window is less than the max-width. If I use the same style with a div, the div does get narrower. (I've used inline css for simplicity in this example.)

<div style="max-width: 400px;background: red;">Div Test</div>
<img alt="" src="myimage.jpg" style="max-width: 400px;">

In the above code, the div and img (correctly) never get larger than 400px. However, when I narrow the browser window the img remains 400px whereas the div gets narrower.

Answer Source

If you give the image a percentage for the margin, it will work just like you expect.

img {
    max-width: 400px;
    width: 100%;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download