How can I fill a div with an image while keeping it proportional?

前端 未结 15 1442
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 00:56

I found this thread — How do you stretch an image to fill a

while keeping the image's aspect-ratio? — that is not entirely the thing that I want.

I h

15条回答
  •  悲&欢浪女
    2020-11-28 01:36

    If I correctly understand what you want, you may leave the width and height attributes off the image to maintain aspect ratio and use flexbox to do the centering for you.

    .fill {
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden
    }
    .fill img {
        flex-shrink: 0;
        min-width: 100%;
        min-height: 100%
    }

    JSFiddle here

    I tested this successfully in IE9, Chrome 31, and Opera 18. But no other browsers were tested. As always you must consider your particular support requirements.

提交回复
热议问题