简体   繁体   English

Div保持原始尺寸的图像而不会拉伸/溢出

[英]Div maintaining original size image without stretching / overflowing

I have an html page like this : 我有一个这样的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> 

this object-fit perfectly fine on google chrome and firefox , but unfortunately not in IE . 此对象适合在google chrome和firefox上很好,但不幸的是在IE中不行。 I don't want to use as background image as I will use this image in a carousel in future ? 我不想用作背景图片,因为将来我会在轮播中使用此图片? is there any alternative so that I fit an image in a fixed height div without stretching and overflowing ? 有没有其他选择可以使图像适合固定高度的div而不会拉伸和溢出? Noted : Object-fit : contain perfectly serve my requirements but failed on IE . 注意:对象适合:完全符合我的要求,但在IE上失败。

Use Modernizr. 使用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');
        }  
    });
}

So you use the object-fit like this: 因此,您可以像这样使用对象拟合:

.post__featured-image {
    width: 120px;
    height: 120px;
    object-fit: cover;
 }

This will copy the src of our image to the background image source of the container. 这会将我们图像的src复制到容器的背景图像源。 Further we change our SCSS a little bit: 此外,我们对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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM