Maintaining aspect ratio with min/max height/width?

馋奶兔 提交于 2019-12-02 22:27:09

The property you're looking for is object-fit. This is one of Opera's innovations, you can read more about it in their 2011 dev article on object-fit (yep, it's been around that long). A few years ago, I wouldn't have been able to recommend it to you, but caniuse shows that everyone else is starting to catch up:

  • Opera 10.6-12.1 (-o- prefix)
  • Chrome 31+
  • Opera 19+
  • Safari 7.1+
  • iOS 8+
  • Android 4.4+

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

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

Using a value of contain will force the image to maintain its aspect ratio no matter what.

Alternately, you might want to use this instead:

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

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

The only way that I know of to possibly accomplish this is by setting either the width or height to auto.

#gallery{
    height: 500px;

    img{
        max-height: 500px;
        width: auto;
    }
}

I don't know if this is possible using only CSS.

However, you may be able to accomplish the same thing with a few lines of 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';
  }
}

This sets the height of all images to be between 200px and 500px. The width will automatically be scaled.

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>

I've been meaning to do something similar, actually. Here's something in jQuery if you're into that.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!