且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在保持比例的同时用图像填充div?

更新时间:2023-11-01 21:13:10

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

<div class="fill">
    <img src="https://lorempizza.com/320/240" alt="" />
</div>

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.