仅在较大时才将图像缩放到父 div,同时使用显式最大宽度 [英] Make images scale to parent div only when larger, all while using an explicit max-width

查看:31
本文介绍了仅在较大时才将图像缩放到父 div,同时使用显式最大宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在较小的屏幕上响应父 div 的图像缩放,但仍然限制为明确的最大宽度:

I can make an image scale responsively to a parent div on smaller screens but still limit to an explicit max width:

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

但是,如果图像小于父 div,它仍然会被拉伸以填充 div.

However, if the image is smaller than the parent div, it is still stretched to fill the div.

有没有办法在不事先知道图像尺寸的情况下,仅在较大时将其缩放至 100%,并在较小时保持其原始尺寸?

Is there a way to have it scale to 100% only when it is larger and maintain its original dimensions when it is smaller, without knowing the image's dimensions beforehand?

推荐答案

您可以设置图片的最大宽度:100%;只有当它大于其父级时才会限制其大小.

You can set the image's max-width: 100%; which would limit its size only if it's bigger than its parent.

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

此处演示:http://jsfiddle.net/LMEwC/

这篇关于仅在较大时才将图像缩放到父 div,同时使用显式最大宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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