CSS图片最大宽度设置为原始图片大小? [英] CSS image max-width set to original image size?

查看:505
本文介绍了CSS图片最大宽度设置为原始图片大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以这样做吗?我让用户将图像上传到width:100%的容器中,但我不希望图像大于其原始大小.非常感谢!

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!

推荐答案

只需不设置图像的width,仅设置max-width.

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

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

(由于auto是默认设置,因此height:auto并不是真正必需的,但是我把它放在这里是为了提醒我我希望图像具有自然的比例.)

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

此代码段包含两个框,一个框小于图像,另一个框大于图像.如您所见,较小框中的图像会按比例缩小,而较大框中的图像则具有正常尺寸.

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>

这篇关于CSS图片最大宽度设置为原始图片大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆