我需要使这张图像拉伸到最大尺寸,而不溢出它的<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>的大小由屏幕的百分比设置,这也是不可预测的。
当前回答
有一个更简单的方法,只使用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的大小而不失真。
其他回答
设置外部容器div的宽度和高度。然后在img上使用下面的样式:
.container img{
width:100%;
height:auto;
max-height:100%;
}
这将帮助你保持你的img的纵横比
如果可以的话,使用背景图像并设置background-size: cover。这将使背景覆盖整个元素。
CSS
div {
background-image: url(path/to/your/image.png);
background-repeat: no-repeat;
background-position: 50% 50%;
background-size: cover;
}
如果你坚持使用内联图像,有几个选项。首先,有
object-fit
此属性作用于图像、视频和其他类似于background-size: cover的对象。
CSS
img {
object-fit: cover;
}
遗憾的是,浏览器的支持并不是很好,直到IE版本11都不支持它。下一个选项使用jQuery
CSS + jQuery
HTML
<div>
<img src="image.png" class="cover-image">
</div>
CSS
div {
height: 8em;
width: 15em;
}
自定义jQuery插件
(function ($) {
$.fn.coverImage = function(contain) {
this.each(function() {
var $this = $(this),
src = $this.get(0).src,
$wrapper = $this.parent();
if (contain) {
$wrapper.css({
'background': 'url(' + src + ') 50% 50%/contain no-repeat'
});
} else {
$wrapper.css({
'background': 'url(' + src + ') 50% 50%/cover no-repeat'
});
}
$this.remove();
});
return this;
};
})(jQuery);
像这样使用插件
jQuery('.cover-image').coverImage();
它将获取一张图像,将其设置为图像包装器元素的背景图像,并从文档中删除img标记。最后你可以用
纯CSS
你可以用这个作为后备。图像会放大以覆盖它的容器,但不会缩小。
CSS
div {
height: 8em;
width: 15em;
overflow: hidden;
}
div img {
min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
max-width: none;
max-height: none;
display: block;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
希望这对大家有所帮助,编码愉快!
感谢CSS3
img
{
object-fit: contain;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
IE和EDGE始终是局外人: http://caniuse.com/#feat=object-fit
如果你能够将图像设置为背景图像,那么你可以这样做,这将裁剪图像而不拉伸它:
<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;
}
试试这个
HTML:
<div class="container"></div>
CSS:
.container{
background-image: url("...");
background-size: 100%;
background-position: center;
}