I was at WordCamp Jacksonville 2017 and one of the speakers said something that caught my attention:
“You often see developers use border-radius: 100%, which works great, except when they start using rectangular images.”
I immediately thought: Well that’s just because they’re doing it wrong! I then went ahead and whipped up a simple Codepen demo to illustrate how it could be done.
Codepen Link: https://codepen.io/iansvo/pen/PmxyvQ
The trick is to create your circle and then absolutely position the image you want to use inside of the circle. In the demo, I use a typical pattern used to center absolutely positioned elements:
img {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
The sneaky part is that you set the border-radius property of a square element to get an even circle. So, since this example involves working with a non-square image, I had to create a square to use for the circle effect. Thankfully, the pen shows an easy way to create a square element without using JavaScript! You start by setting your target square element’s width, then use the ::after pseudo element to enforce the square shape:
.circle::after {
content: '';
display: block;
padding-bottom: 100%;
}
The padding-bottom property is a percentage that is inherited from the element’s width, which creates a square, even if the circle element has a fluid width.