I want to make a centered circular image from rectangle photo. The photo\'s dimensions is unknown. Usually it\'s a rectangle form. I\'ve tried a lot of methods:
CSS:
The best way I've been able to do this is with using the new css object-fit
(1) property and the padding-bottom
(2) hack.
You need a wrapper element around the image. You can use whatever you want, but I like using the new HTML picture
tag.
.rounded {
display: block;
width: 100%;
height: 0;
padding-bottom: 100%;
border-radius: 50%;
overflow: hidden;
}
.rounded img {
width: 100%;
height: 100%;
object-fit: cover;
}
/* These classes just used for demo */
.w25 {
width: 25%;
}
.w50 {
width: 50%;
}
<div class="w25">
<picture class="rounded">
<img src="https://i.imgur.com/A8eQsll.jpg">
</picture>
</div>
<!-- example using a div -->
<div class="w50">
<div class="rounded">
<img src="https://i.imgur.com/A8eQsll.jpg">
</div>
</div>
<picture class="rounded">
<img src="https://i.imgur.com/A8eQsll.jpg">
</picture>
CSS Image size, how to fill, not stretch?
Maintain the aspect ratio of a div with CSS
If you can live without the <img>
tag, I suggest you use the photo as a background image.
.cropcircle{
width: 250px;
height: 250px;
border-radius: 100%;
background: #eee no-repeat center;
background-size: cover;
}
#image1{
background-image: url(http://www.voont.com/files/images/edit/7-ridiculous-ways-boost-self-esteem/happy.jpg);
}
<div id="image1" class="cropcircle"></div>
I know many of the solutions mentioned above works, you can as well try flex.
But my image was rectangular and not fitting properly. so this is what i did.
.parentDivClass {
position: relative;
height: 100px;
width: 100px;
overflow: hidden;
border-radius: 50%;
margin: 20px;
display: flex;
justify-content: center;
}
and for the image inside, you can use,
child Img {
display: block;
margin: 0 auto;
height: 100%;
width: auto;
}
This is helpful when you are using bootstrap 4 classes.