Skip to content

Instantly share code, notes, and snippets.

@geoffroymontel
Last active December 15, 2017 01:12
Show Gist options
  • Save geoffroymontel/9019411 to your computer and use it in GitHub Desktop.
Save geoffroymontel/9019411 to your computer and use it in GitHub Desktop.
Crop and center image with CSS only

Easily resize, crop and center an image on any container with CSS

<div id="graphic">lorem ipsum</div>
#graphic {
  width: 300px;
  height: 200px;
  position: relative;
}
#graphic:before {
  content: '';
  
  position: absolute;
  z-index: -1;
  background-position: center center;
  background-size: cover;
  bottom: 0;
  top: 0;
  left: 0;
  right: 0;
  
  background-image: url(http://brocoli.org/media/img/artists/minizza2.jpg);
}

Or

<div id="crop">
  lorem ipsum
  <div id="image" />
</div>
#crop {
  color: white;
  width: 200px;
  height: 200px;
  position: relative;
  background-color: hsl(20%,20%,100%);
}
#image {
  z-index: -1;
  position: absolute;
  background-position: center center;
  background-size: cover;
  bottom: 0;
  top: 0;
  left: 0;
  right: 0;

  background-image: url(http://brocoli.org/media/img/artists/minizza2.jpg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment