Create a circle avatar from a rectangle image keeping proportions and just using centre of image
You can set the image as the background of an element, set its background-size to cover
, and then use border-radius to round the edges.
#avatar {
/* This image is 687 wide by 1024 tall, similar to your aspect ratio */
background-image: url('http://i.stack.imgur.com/Dj7eP.jpg');
/* make a square container */
width: 150px;
height: 150px;
/* fill the container, preserving aspect ratio, and cropping to fit */
background-size: cover;
/* center the image vertically and horizontally */
background-position: top center;
/* round the edges to a circle with border radius 1/2 container size */
border-radius: 50%;
}
<div id="avatar"></div>
Another solution is to set the sizes for img and use "object-fit: cover;". It will do the same as the "background-size:cover" without messing with background images.
img {
object-fit: cover;
border-radius:50%;
width: 150px;
height: 150px;
}
<img src="http://i.stack.imgur.com/Dj7eP.jpg" />
I found it on Chris Nager post. - 1
Edit:
As @prograhammer mentioned, this doesn't work on IE. Edge supports it only on <img>
tags.
Partial support in Edge refers to
object-fit
only supporting<img>
- 2
Edit 2: This post of Primož Cigler shows how to use Modernizr to add a fallback support for IE but, in this case, you will need to add a wrapper to de image.
If the image is required to be in the HTML rather than a background image
.wrapper {
width:150px;
height:150px;
margin: 25px auto;
overflow: hidden;
border-radius:50%;
position: relative;
}
.wrapper img {
position: absolute;
top:50%;
left:50%;
transform: translate(-50%,-50%)
}
<div class="wrapper">
<img src="http://lorempixel.com/output/business-q-c-640-480-4.jpg" alt="" />
</div>