If you’ve got a rounded corner on both the outside, and the inside of an element that both have the same value, it looks pretty weird.
See the Pen Identical corners by piccalilli (@piccalilli) on CodePen.
The reason for this is even though they match in value—say, 20px
—they don’t match mathematically. Even though they are the same, the inner radius looks awkward and oversized.
Luckily, there’s a little formula we can use to create perfect rounded corners that are relatively sized:
- Code language
- text
P + R = RO
These variables are:
P
: the padding (space) between each radiusR
: the inner (original) radiusRO
: the calculated outer radius
As you can see, using this formula gives us a perfect, relative radius. Now let’s do it with HTML and CSS.
We’re going to start with this HTML:
- Code language
- html
<div class="matched-radius"> <div class="matched-radius__inner"></div> </div>
The matched-radius__inner
element’s radius will be R
and the matched-radius
element’s radius will be RO
. The P
is the matched-radius
element’s padding value.
Let’s start off with the outer element’s CSS.
- Code language
- css
.matched-radius { --matched-radius-padding: 8px; --matched-radius-inner-size: 12px; padding: var(--matched-radius-padding); border-radius: calc( var(--matched-radius-inner-size) + var(--matched-radius-padding) ); }
There’s two CSS Custom Properties for the inner radius size and the padding. When configured, these allow the outer radius to be calculated. We do this with calc()
.
Now, let’s add some CSS for the inner element.
- Code language
- css
.matched-radius__inner { border-radius: var(--matched-radius-inner-size); }
And that’s it! A few lines of CSS that guarantees your rounded corners are always going to look great. An extra bonus that it’s completely configurable too, so you can drop this CSS utility wherever you need it.
Here’s the utility code in full, so you can copy and paste it easier:
- Code language
- css
.matched-radius { --matched-radius-padding: 8px; --matched-radius-inner-size: 12px; padding: var(--matched-radius-padding); border-radius: calc( var(--matched-radius-inner-size) + var(--matched-radius-padding) ); } .matched-radius__inner { border-radius: var(--matched-radius-inner-size); }
Check out this demo, too, where you can tweak the padding and radius to see the formula working.
See the Pen Relative rounded corners by piccalilli (@piccalilli) on CodePen.