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

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

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.

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay