我需要使这张图像拉伸到最大尺寸,而不溢出它的<div>或倾斜图像。
我无法预测图像的纵横比,所以没有办法知道是否使用:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
我不能同时使用(即style="width: 100%;高度:100%;"),因为这将拉伸图像以适应<div>。
<div>的大小由屏幕的百分比设置,这也是不可预测的。
我需要使这张图像拉伸到最大尺寸,而不溢出它的<div>或倾斜图像。
我无法预测图像的纵横比,所以没有办法知道是否使用:
<img src="url" style="width: 100%;">
or
<img src="url" style="height: 100%;">
我不能同时使用(即style="width: 100%;高度:100%;"),因为这将拉伸图像以适应<div>。
<div>的大小由屏幕的百分比设置,这也是不可预测的。
当前回答
要使此图像拉伸到最大可能的大小,而不会溢出或倾斜图像。
应用……
img {
object-fit: cover;
height: -webkit-fill-available;
}
图像的样式。
其他回答
如果你能够将图像设置为背景图像,那么你可以这样做,这将裁剪图像而不拉伸它:
<div style="background-image: url(...); background-size: cover; width: 100%; height: 100%;"></div>
如果你需要坚持使用<img>标签,那么从2019年开始,你现在可以使用对象适合css属性,它接受以下值: 填充|包含|覆盖|无|缩小
参见https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
举个例子,你可以有一个存放图像的容器:
<div class="container">
<img src="" class="container_img" />
</div>
.container {
height: 50px;
width: 50%;
}
.container_img {
height: 100%;
width: 100%;
object-fit: cover;
}
有一个更简单的方法,只使用CSS和HTML:
HTML:
<div
class="fill"
style="background-image: url('path/to/image.jpg');">
</div>
CSS:
.fill {
background-size: cover;
background-position: center;
width: 100%;
height: 100%;
}
这将把你的图像作为背景,并拉伸它以适应div的大小而不失真。
感谢CSS3
img
{
object-fit: contain;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
IE和EDGE始终是局外人: http://caniuse.com/#feat=object-fit
这不是一个完美的解决方案,但这个CSS可能会有所帮助。缩放是这段代码的工作原理,理论上,对于小图像,因子应该是无限大的,但在大多数情况下,2、4或8就可以了。
#myImage {
zoom: 2; //increase if you have very small images
display: block;
margin: auto;
height: auto;
max-height: 100%;
width: auto;
max-width: 100%;
}
试试这个
HTML:
<div class="container"></div>
CSS:
.container{
background-image: url("...");
background-size: 100%;
background-position: center;
}