我正在处理图像,我遇到了纵横比问题。
<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 {
width: 500px;
height: 600px;
object-fit: contain;
position: relative;
top: 50%;
transform: translateY(-50%);
}
其他回答
要强制图像符合精确的大小,您不需要编写太多代码。太简单了
国际货币基金组织{宽度:200px;高度:自动;对象拟合:包含;/*按图像大小调整徽标*/-o-object-fit:contain;/*为opera浏览器安装徽标*/对象位置:顶部;/*设置徽标位置*/-o对象位置:顶部;/*opera浏览器的徽标位置*/}<img src=“http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png“alt=”徽标“>
您可以创建如下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
我建议对于响应式方法,最佳做法是使用视口单位和最小/最大属性,如下所示:
img{
display: block;
width: 12vw;
height:12vw;
max-width:100%;
min-width:100px;
min-height:100px;
object-fit:contain;
}
您可以将容器设置为显示:伸缩和对齐项目:居中(其他对齐项目值也适用)。您也可以在图像本身上设置对齐自身,而不是对齐项目。
如果应用程序可以具有任何纵横比或分辨率的图像,则可以像此链接中那样管理高度和宽度。
这使用Javascript和HTML
https://stackoverflow.com/a/65090175/13338731