Maintaining aspect ratio with min/max height/width?

后端 未结 4 550
無奈伤痛
無奈伤痛 2020-12-28 14:19

I have a gallery on my site where users can upload images.

I would like the images to sit in a div that maintains its height, the images should be no larger than 500

4条回答
  •  情深已故
    2020-12-28 14:58

    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;
    }

提交回复
热议问题