CSS 图像最大宽度设置为原始图像大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24197730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:34:14  来源:igfitidea点击:

CSS image max-width set to original image size?

cssimage

提问by nikk wong

Can you do this? I'm having users upload images into a container that is width:100%, but I don't want the images to be larger than their original size. Many thanks!

你能做这个吗?我让用户将图像上传到宽度为 100% 的容器中,但我不希望图像大于其原始尺寸。非常感谢!

回答by Mr Lister

Just don't set the widthof the image, only the max-width.

只是不要设置width图像的 ,只设置max-width.

img {max-width:100%; height:auto}

(height:autois not really necessary, since autois the default, but I put it in there as a reminder to myself that I want the image to have its natural proportions.)

height:auto并不是真的有必要,因为这auto是默认设置,但我把它放在那里是为了提醒自己,我希望图像具有自然的比例。)

This snippet has two boxes, one that is smaller than the image and one that is larger. As you can see, the image in the smaller box gets scaled down, while the one in the bigger box has its normal size.

这个片段有两个框,一个比图像小,一个比图像大。如您所见,较小框中的图像按比例缩小,而较大框中的图像具有正常大小。

div {border:2px outset green; margin:6px 0}
.box1 {width:100px; height:70px;}
.box2 {width:200px; height:100px;}
img {max-width:100%; height:auto}
<div class="box1">
    <img src="https://i.stack.imgur.com/FuQYf.png" alt="" />
</div>
<div class="box2">
    <img src="https://i.stack.imgur.com/FuQYf.png" alt="" />
</div>

回答by Nancy Hastings-Trew

You can set the max width of the image in a style tag on the image itself. Then in the style sheet set the display type to "block", the width to whatever percentage of the container you want, and the height to auto. Then add margin: 0px auto to that and it should center perfectly and will never be larger that it's original size.

您可以在图像本身的样式标签中设置图像的最大宽度。然后在样式表中将显示类型设置为“块”,宽度设置为您想要的容器的任何百分比,高度设置为自动。然后添加 margin: 0px auto ,它应该完美居中并且永远不会比它的原始尺寸大。

If these are user-uploaded images and you are using PHP for example, find the image width by using getImageSize() and add the style tag programmatically to the image.

如果这些是用户上传的图像并且您使用的是 PHP,例如,使用 getImageSize() 查找图像宽度并以编程方式将样式标记添加到图像。