DEV Community 👩‍💻👨‍💻

Jim Frenette
Jim Frenette

Posted on • Originally published at jimfrenette.com

Images Larger than Container CSS

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

Screen capture of 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)

Collapse
kasparsz profile image
Kaspars Zuks

Or just use "object-fit: cover;"

Collapse
jimfrenette profile image
Jim Frenette Author • Edited on

I guess that depends on your supported browser spec. - caniuse.com/#search=object-fit

Collapse
kasparsz profile image
Kaspars Zuks

I use this polyfill, haven't had any major issues in older browsers with it npmjs.com/package/object-fit-images

Thread Thread
jimfrenette profile image
Jim Frenette Author

Thanks for the info! I will have to update my original post with this resource.

🤔 Did you know?

 
🌚 Dark mode is available in Settings.