我正在处理图像,我遇到了纵横比问题。
<img src="big_image.jpg" width="900" height="600" alt="" />
如您所见,高度和宽度已经指定。我为图像添加了CSS规则:
img {
max-width: 500px;
}
但对于big_image.jpg,我得到的宽度=500,高度=600。如何设置图像的大小,同时保持其纵横比。
我正在处理图像,我遇到了纵横比问题。
<img src="big_image.jpg" width="900" height="600" alt="" />
如您所见,高度和宽度已经指定。我为图像添加了CSS规则:
img {
max-width: 500px;
}
但对于big_image.jpg,我得到的宽度=500,高度=600。如何设置图像的大小,同时保持其纵横比。
当前回答
与这里的一些答案非常相似,但在我的案例中,我的图像有时更高,有时更大。
这种风格就像一种魅力,确保所有图像都使用所有可用空间,保持比例而不是剪切:
.img {
object-fit: contain;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
其他回答
只需将此添加到css中,它将自动收缩和扩展,并保持原始比例。
img {
display: block;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
这里有一个解决方案:
object-fit: cover;
width: 100%;
height: 250px;
您可以调整宽度和高度以满足您的需要,对象拟合属性将为您进行裁剪。
有关对象拟合属性和兼容性表的可能值的更多信息,请参见:https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
这是精神上的。使用比例缩小属性-它可以自行解释。
内联样式:
<img src='/nic-cage.png' style={{ maxWidth: '50%', objectFit: 'scale-down' }} />
这将阻止flex拉伸它。在这种情况下,图像将达到其父容器宽度的50%,并且高度将缩小以匹配。
保持简单。
可以使用纵横比属性css
.my-image {
aspect-ratio: 1/1; // square
aspect-ratio: 16/9; // wide screen 1080p
aspect-ratio: 4/3;
aspect-ratio: 2/3;
}
删除“height”属性。
<img src="big_image.jpg" width="900" alt=""/>
通过指定这两个选项,可以更改图像的纵横比。只需设置一个即可调整大小,但保持纵横比。
(可选)限制过大:
<img src="big_image.jpg" width="900" alt="" style="max-width:500px; height:auto; max-height:600px;"/>