如果可以的话,使用背景图像并设置
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
标签。最后你可以使用。
Pure 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%);
}
希望这能对某人有所帮助,愉快地编码!
object-fit
,请查看(并点赞)下面@daniels的回答。 - ᴍᴇʜᴏᴠ