首页 文章

保持纵横比与最小/最大高度/宽度?

提问于
浏览
17

我的网站上有一个用户可以上传图片的图库 .

我希望图像位于保持其高度的div中,图像的高度不应超过500px . 宽度应自动保持纵横比 .

HTML:

<div id="gallery">
    <img src="uploads/my-dynamic-img.jpg">
</div>

我试过这个CSS:

#gallery{
    height: 500px;

    img{
        max-height: 500px;
        max-width: 100%;
    }
}

以上效果很好,画廊总是500px高,图像高度不超过500px . 我遇到问题虽然图像较小,但如果用户上传的图片非常小,我希望它至少可以达到200px . 我知道这可以通过在图像上设置 min-height 来实现,问题是,如果图像的高度小于200像素,但是说宽度为2000像素,则图像的高度会被吹得高达200像素,然后是高宽比被拧紧,因为图像比图像父div更宽 .

我怎样才能达到最小高度但保持纵横比?

4 回答

  • 25

    您要找的房产是 object-fit . 这是Opera的创新之一,你可以在他们的2011 dev article on object-fit中阅读更多关于它的内容(是的,它已经能够向你推荐它,但是caniuse表明其他人都开始追赶:

    • Opera 10.6-12.1(-o-前缀)

    • Chrome 31

    • 歌剧19

    • Safari 7.1

    • iOS 8

    • Android 4.4

    http://caniuse.com/#search=object-fit

    #gallery img {
        -o-object-fit: contain;
        object-fit: contain;
    }
    

    使用 contain 的值将强制图像保持其纵横比,无论如何 .

    或者,您可能希望使用此代码:

    #gallery img {
        -o-object-fit: cover;
        object-fit: cover;
        overflow: hidden;
    }
    

    http://sassmeister.com/gist/9b130efdae95bfa4338e

  • 3

    我知道可能实现此目的的唯一方法是将 widthheight 设置为 auto .

    #gallery{
        height: 500px;
    
        img{
            max-height: 500px;
            width: auto;
        }
    }
    
  • 1

    我不知道这是否只能使用CSS .

    但是,您可以使用几行JavaScript完成相同的操作:

    var img= document.querySelectorAll('img');
    for(var i = 0 ; i < img.length ; i++) {
      img[i].onload= function() {
        var h= this.naturalHeight;
        h= Math.min(500,Math.max(200,h));
        this.style.height= h+'px';
      }
    }
    

    这会将所有图像的高度设置为200px到500px之间 . 宽度将自动缩放 .

    var img= document.querySelectorAll('img');
    for(var i = 0 ; i < img.length ; i++) {
      img[i].onload= function() {
        var h= this.naturalHeight;
        h= Math.min(500,Math.max(200,h));
      }
    }
    
    #gallery{
      height: 500px;
      width: 400px;
      overflow: hidden;
    }
    
    <div id="gallery">
      <img src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo-med.png">
    
    </div>
    
  • 1

    实际上,我一直想做类似的事情 . 如果你是这样的话,这里有jQuery的东西 .

    SCSS:

    #gallery {
      height: 500px;
    
      img {
        max-height: 100%;
      }
    
      .small {
        width: 100%;
        max-width: 500px;
        height: auto;
      }
    
      .regular {
        width: auto;
        min-height: 200px;
      }
    }
    

    jQuery的:

    $( 'img' ).each( function() {
    
      var imageWidth = parseFloat( $( this ).css( 'width' ) );
      var imageHeight = parseFloat( $( this ).css( 'height' ) );
    
      if( imageHeight <= 200 && imageWidth >= 200 ) {
        $( this ).addClass( 'small' );
      }
      else {
        $( this ).addClass( 'regular' );
      }
    });
    

    CodePen

相关问题