This will center the image inside of a element when the elements height and/or width is smaller than the image. This works well when you have image assets of various aspect ratios that you want to display as thumbs that are the same size.
demo
HTML
<ul class="thumbnails">
<li>
<img src="https://via.placeholder.com/400x300/9932CC/FFFFFF">
</li>
<li>
<img src="https://via.placeholder.com/500x300/7FFFD4/000000">
</li>
<li>
<img src="https://via.placeholder.com/300x200/87CEFA/000000">
</li>
<li>
<img src="https://via.placeholder.com/300x400/F4A460/000000">
</li>
</ul>
CSS
ul.thumbnails {
display: flex;
flex-wrap: wrap;
}
ul.thumbnails li {
height: 150px;
border: 4px solid #FFF;
overflow: hidden;
position: relative;
width: 150px;
}
ul.thumbnails li img {
position: absolute;
top: -9999px;
bottom: -9999px;
left: -9999px;
right: -9999px;
margin: auto;
width: 250px;
}
Originally published at jimfrenette.com/css/images-larger-than-container
Top comments (4)
Or just use "object-fit: cover;"
I guess that depends on your supported browser spec. - caniuse.com/#search=object-fit
I use this polyfill, haven't had any major issues in older browsers with it npmjs.com/package/object-fit-images
Thanks for the info! I will have to update my original post with this resource.