我正在处理图像,我遇到了纵横比问题。
<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。如何设置图像的大小,同时保持其纵横比。
当前回答
您可以创建如下div:
<div class="image" style="background-image:url('/to/your/image')"></div>
并使用此css设置其样式:
height: 100%;
width: 100%;
background-position: center center;
background-repeat: no-repeat;
background-size: contain; // this can also be cover
其他回答
只需将此添加到css中,它将自动收缩和扩展,并保持原始比例。
img {
display: block;
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
使用伪元素进行垂直对齐怎么样?这更少的代码用于旋转木马,但我想它适用于每个固定大小的容器。它将保持纵横比,并在顶部/底部或左侧/写入最短尺寸时插入@灰色暗条。同时,图像通过文本对齐水平居中,通过伪元素垂直居中。
> li {
float: left;
overflow: hidden;
background-color: @gray-dark;
text-align: center;
> a img,
> img {
display: inline-block;
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
margin: auto;
text-align: center;
}
// Add pseudo element for vertical alignment of inline (img)
&:before {
content: "";
height: 100%;
display: inline-block;
vertical-align: middle;
}
}
这里有一个解决方案:
img {
width: 100%;
height: auto;
object-fit: cover;
}
这将确保图像始终覆盖整个父对象(向下和向上缩放)并保持相同的纵横比。
如果应用程序可以具有任何纵横比或分辨率的图像,则可以像此链接中那样管理高度和宽度。
这使用Javascript和HTML
https://stackoverflow.com/a/65090175/13338731
我建议对于响应式方法,最佳做法是使用视口单位和最小/最大属性,如下所示:
img{
display: block;
width: 12vw;
height:12vw;
max-width:100%;
min-width:100px;
min-height:100px;
object-fit:contain;
}