July 10, 2017

CSS-Cropping: How To Preserve Aspect Ratio

I do a lot of 'profile' type sites but one thing I've always struggled with is the 'circular' profile image due to the aspect-ratio changing.

I do a lot of "profile" type sites - a basic profile image with descriptions and maybe some social media links. One thing that I've always struggled with was the 'circular' profile image. I circumvented this for a while by hard-cropping in photoshop or requesting square images, then slapping the border-radius on it and calling it a day.
But now, I'm trying to build a site that has dynamically sized images, which presents a problem: setting a hard width and height screws with the aspect ratio of the image. After some thought and Googling, I was able to come up with this solution:

<img class='circle' src='image.png' />

img.circle {
  -o-object-fit: cover;
  object-fit: cover;
  height: 150px;
  width: 150px;
  border-radius: 50%;

Which presents this:

See the Pen Object-fit by Nate Northway (@the_Northway) on CodePen.

I definitely feel like this is the most elegant and straight-forward solution to this problem. I'm excited to put this into regular use.