DEV Community

Jim Frenette
Jim Frenette

Posted on • Originally published at jimfrenette.com

3 2

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>
Enter fullscreen mode Exit fullscreen mode
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;
}
Enter fullscreen mode Exit fullscreen mode

Originally published at jimfrenette.com/css/images-larger-than-container

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (4)

Collapse
 
kasparsz profile image
Kaspars Zuks

Or just use "object-fit: cover;"

Collapse
 
jimfrenette profile image
Jim Frenette • Edited

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

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay