本文翻译自:Resize image proportionally with CSS? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
Is there a way to resize (scale down) images proportionally using ONLY CSS? 有没有办法使用ONLY CSS按比例调整大小(缩小)图像?
I'm doing the JavaScript way, but just trying to see if this is possible with CSS. 我正在做JavaScript方式,但只是想看看CSS是否可行。
#1楼
参考:https://stackoom.com/question/3Ix5/使用CSS按比例调整图像大小-重复
#2楼
Control size and maintain proportion : 控制尺寸和保持比例:
#your-img {
height: auto;
width: auto;
max-width: 300px;
max-height: 300px;
}
#3楼
img {
max-width:100%;
}
div {
width:100px;
}
with this snippet you can do it in a more efficient way 使用此代码段,您可以更有效地执行此操作
#4楼
Notice that width:50%
will resize it to 50% of the available space for the image, while max-width:50%
will resize the image to 50% of its natural size . 请注意, width:50%
会将其大小调整为图像可用空间的50% ,而max-width:50%
会将图像大小调整为其自然大小的50% 。 This is very important to take into account when using this rules for mobile web design, so for mobile web design max-width
should always be used. 在将此规则用于移动网页设计时,这一点非常重要,因此对于移动网页设计,应始终使用max-width
。
#5楼
To scale an image by keeping its aspect ratio 通过保持纵横比来缩放图像
Try this, 试试这个,
img {
max-width:100%;
height:auto;
}
#6楼
If it's a background image, use background-size:contain. 如果是背景图片,请使用background-size:contains。
Example css: 示例css:
#your-div {
background: url('image.jpg') no-repeat;
background-size:contain;
}