Jordan McMahon
Jordan McMahon

Reputation: 1

Fitting an image inside of a circle when the aspect ratio is not 1:1

I have a form where users upload an avatar of themselves. Sometimes the file they upload is a perfect square, but often it's not. Here's the HTML I'm using to display the image:

<img src="<?php echo $image; ?>" style="border-radius: 50%; border: 1px #000 solid; height: 70px; width: 70px;"/>

And here's how it turns out depending on the aspect ratio of the image they upload:

enter image description here enter image description here

What I would like to achieve:

Is there a good way to do this and account for many different scenarios of image sizes?

I've tried everything!

Upvotes: -1

Views: 109

Answers (1)

Brett Donald
Brett Donald

Reputation: 14340

Use object-fit and object-position.

body {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1em;
}

img {
  border: 2px solid black;
}

.i1 {
  border-radius: 50%;
  height: 120px;
  width: 120px;
  object-fit: cover;
  object-position: center;
}
<img class="i0" src="http://picsum.photos/id/219/220/140">
<img class="i1" src="http://picsum.photos/id/219/220/140">

Upvotes: 1

Related Questions