How to set max width of an image in CSS

user1315305 picture user1315305 · Jun 18, 2012 · Viewed 265.7k times · Source

On my website I would like to display images uploaded by user in a new window with a specific size (width: 600px). The problem is that the images may be big. So if they are bigger than these 600px, I would like to resize them, preserving the aspect ratio.

I tried the max-width CSS property, but it doesn't work: the image's size doesn't change.

Is there any way to solve this problem?

HTML:

<div id="ImageContainerr">
    <img src="DisplayImage.do?ad_id=${requestScope.advert.id}" class="Image" />
</div>

CSS:

img.Image { max-width: 100%;}
div#ImageContainer { width: 600px; }

I also tried setting the max-width: 600px for an image, but doesn't work. The image is streamed from a servlet (it's stored outside Tomcat's webapps folder).

Answer

sandeep picture sandeep · Jun 18, 2012

You can write like this:

img{
    width:100%;
    max-width:600px;
}

Check this http://jsfiddle.net/ErNeT/