Interesting CSS shapes with border-radius
TL;DR Create interesting shapes by separating border-radius values with a slash.
We're all well acquainted with border-radius. Most commonly, I'll use it for rounding the corners of a button, or creating a circle using a 50%
value. It's rare that I ever need to define different values for each corner.
Until now, that was as far as my border-radius knowledge went. I was unaware that you could separate values with a slash and if I'm completely honest, I wasn't entirely sure how a border-radius value of 50%
created a circle.
Creating a circle with 50% radius
So, how does border-radius: 50%;
create a circle? Check out this snippet from the W3C:
“If values are given before and after the slash, then the values before the slash set the horizontal radius and the values after the slash set the vertical radius. If there is no slash, then the values set both radii equally.” W3C
Ahhhh, this makes sense now. But to explain this in more detail, let's take a look at a single corner: border-top-left-radius: 50%;
When we add a border-radius to a corner using a single value, we're applying the value to both the horizontal and the vertical line coming out of that corner. This is the point at which the radius will begin on the line and with a value of 50%
it'll start halfway along it.
Therefore, when border-radius: 50%;
is applied, all four corners begin their radius halfway down the line, creating the illusion of a circle.
Using four different values
border-radius: 40% 20% 60% 30%;
By defining four values, each corner is styled individually, starting with the top left corner and working clockwise around the box.
But, as we've already covered, each value is actually applied twice: to both lines coming out of the four corners.
Using eight values with a slash
When using four values, the browser actually interprets it as eight. Here's the previous example shown as eight individual values:
border-radius: 40% 20% 60% 30% / 40% 20% 60% 30%;
The first four numbers represent the horizontal lines coming from each corner, whereas the four numbers after the /
represent the vertical lines.
This can be a bit tricky to wrap your head around at first, but gives you a lot of control over the shapes that you can create.
Fortunately, the excellent 9elements blog article (of which this post is inspired) also includes a handy visual tool for generating your custom shapes: