Reputation: 2033
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.
Upvotes: 3
Views: 1893
Reputation: 27225
You need to give the div an explicit width (e.g. ˋ100%ˋ), otherwise it will use the actual width of the image (implicit ˋwidth: autoˋ) as a reference, which could be more than ˋ100%ˋ:
<img alt="" src="myimage.jpg" style="max-width: 400px; width: 100%;">
Upvotes: 3
Reputation: 9348
If you give the image a percentage for the margin
, it will work just like you expect.
img {
max-width: 400px;
width: 100%;
}
Upvotes: 5
Reputation: 1206
There's no need to set the max-width:
of the image as a set number of pixels if the container is a set width, just set the img to max-width:100%
Upvotes: 1