CSS-Cropping: How To Preserve Aspect Ratio

July 10, 2017
CSS and SASS Frontend

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.

No Comments...yet

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

Regex Cheatsheet

From May 23, 2017

I’ve been writing some regex lately and compiled this handy little cheat sheet. Hopefully it helps you quickly write regex. I know I’ll be using it!

Read This Article
Next Post

Comparing Frameworks

From February 8, 2018

Gittr is looking for a new front end solution and we’re going to be comparing three frameworks – Bootstrap, Bulma, and Semantic UI – to find what works best

Read This Article