如何在 CSS 中设置图像的最大宽度

在我的网站,我想显示图像上传的用户在一个新的窗口与特定大小(width: 600px)。问题是图像可能很大。因此,如果他们是大于这些 600px,我想调整他们的大小,保留纵横比。

我尝试了 max-width CSS 属性,但它不工作: 图像的大小不变。

有办法解决这个问题吗?

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; }

我还试着为一个图像设置 max-width: 600px,但是不起作用。该图像从一个 servlet (它存储在 Tomcat 的 webapps 文件夹之外)流。

337405 次浏览

You can write like this:

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

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

Try this

 div#ImageContainer { width: 600px; }
#ImageContainer img{ max-width: 600px}

Given your container width 600px.

If you want only bigger images than that to fit inside, add: CSS:

#ImageContainer img {
max-width: 600px;
}

If you want ALL images to take the avaiable (600px) space:

#ImageContainer img {
width: 600px;
}

Your css is almost correct. You are just missing display: block; in image css. Also one typo in your id. It should be <div id="ImageContainer">

img.Image { max-width: 100%; display: block; }
div#ImageContainer { width: 600px; }
<div id="ImageContainer">
<img src="http://placehold.it/1000x600" class="Image">
</div>

The problem is that img tag is inline element and you can't restrict width of inline element.

So to restrict img tag width first you need to convert it into a inline-block element

img.Image{
display: inline-block;
}

I see this hasn't been answered as final.

I see you have max-width as 100% and width as 600. Flip those.

A simple way also is:

     <img src="image.png" style="max-width:600px;width:100%">

I use this often, and then you can control individual images as well, and not have it on all img tags. You could CSS it also like below.

 .image600{
width:100%;
max-width:600px;
}


<img src="image.png" class="image600">

Wrap the element in a div with the fixed width/height:

<div style="width: 600px;">
<img src="whatever" />
</div>