Skip to content

Instantly share code, notes, and snippets.

@miquels
Last active June 19, 2024 20:28
Show Gist options
  • Save miquels/5f41eb90d9ec95eabbcac67255f0c7fa to your computer and use it in GitHub Desktop.
Save miquels/5f41eb90d9ec95eabbcac67255f0c7fa to your computer and use it in GitHub Desktop.
object-fit equivalents in pure css

object-fit equivalents in pure css

HTML

<div class="container">
  <img src="http://thetvdb.com/banners/fanart/original/78804-61.jpg">
</div>

Object-fit:contain

.container {
  position:relative;
  height: 600px;
  width: 600px;
}
.container img {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  max-width: 100%;
  max-height: 100%;
  margin: auto;
}

Object-fit: cover

This is AFAIK not possible without javascript. Depending on the aspect ratio of the containing element vs. the aspect ratio of the image you have to set either

width: 100%;
height: auto;

or

width: auto;
height: 100;
.container {
  width: 540px;
  height: 270px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
.container img {
  width: 100%;
  height: auto;
}
@hejiaji
Copy link

hejiaji commented Jul 23, 2021

If the image is a smaller size, this CSS won't scale up as object-fit: contain does

@omuleanu
Copy link

Thank You

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment