[英]Div maintaining original size image without stretching / overflowing
我有一个这样的html页面:
<html> <head> <style> .main { max-width:500px; min-height:500px; margin:auto; } .image-container { width:100%; background-color:black; min-height: 200px; height:300px; } img { object-fit: contain; height:200px; } </style> </head> <body> <div class="main"> <div class="image-container"> <img src="https://i.gyazo.com/3a4b9b23d8d1a179b75472d58bc55fe3.jpg" style="width:100%"/> </div> </div> </body> </html>
此对象适合在google chrome和firefox上很好,但不幸的是在IE中不行。 我不想用作背景图片,因为将来我会在轮播中使用此图片? 有没有其他选择可以使图像适合固定高度的div而不会拉伸和溢出? 注意:对象适合:完全符合我的要求,但在IE上失败。
使用Modernizr。
if ( ! Modernizr.objectfit ) {
$('.post__image-container').each(function () {
var $container = $(this),
imgUrl = $container.find('img').prop('src');
if (imgUrl) {
$container
.css('backgroundImage', 'url(' + imgUrl + ')')
.addClass('compat-object-fit');
}
});
}
因此,您可以像这样使用对象拟合:
.post__featured-image {
width: 120px;
height: 120px;
object-fit: cover;
}
这会将我们图像的src复制到容器的背景图像源。 此外,我们对SCSS进行了一些更改:
.post {
&__image-container {
width: 120px; // the same width and height as for the <img>
height: 120px;
&.compat-object-fit {
background-size: cover;
background-position: center center;
.post__featured-image { // hide image if object fit is not supported - opacity to 0 for the link area
opacity: 0;
}
}
}
&__featured-image {
width: 120px;
height: 120px;
object-fit: cover;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.