Maintaining aspect ratio with min/max height/width?

后端 未结 4 553
無奈伤痛
無奈伤痛 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 15:18

    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

提交回复
热议问题