如何自动调整大图像的大小,使其适合较小宽度的 div 容器,同时保持其宽高比?
解决方法
不要对图像标签应用明确的宽度或高度。相反,给它:
max-width:100%;max-height:100%;
此外,height: auto;
如果您只想指定宽度。
示例:http : //jsfiddle.net/xwrvxser/1/
img {
max-width: 100%;
max-height: 100%;
}
.portrait {
height: 80px;
width: 30px;
}
.landscape {
height: 30px;
width: 80px;
}
.square {
height: 75px;
width: 75px;
}
Portrait Div
<div className="portrait">
<img src="http://i.stack.imgur.com/xkF9Q.jpg" />
</div>
Landscape Div
<div className="landscape">
<img src="http://i.stack.imgur.com/xkF9Q.jpg" />
</div>
Square Div
<div className="square">
<img src="http://i.stack.imgur.com/xkF9Q.jpg" />
</div>
第二种方法
使用 object-fit
<img style="height: 100%; width: 100%; object-fit: contain" />