csscalc

Maintaining Consistent Visual Border-Radius for Buttons of Different Sizes Using CSS calc()


I’m currently working on a project that involves two buttons of different sizes. Both buttons are designed with the same border-radius of 6px. However, when rendered in the browser, they appear to have different border-radius values. The smaller button seems to have a larger border-radius compared to the larger button, despite both being set to the same pixel value.

My goal is to make the smaller button appear as a scaled-down version of the larger button, maintaining the same visual border-radius. This means that both buttons should look identical in terms of their border-radius, regardless of their size.

Is there a way to achieve this using CSS calc()? I’m asking for a solution involving calc() because I’m not allowed to modify the 6px value as it’s going to be used as a variable in my project.

.small {
    padding: 0.1rem 0.6rem;
    font-size: 0.475rem;
    color: white;
    border-radius: 6px;
    background-color: red;
    border: none;
}

.large {
    padding: .5rem 3rem;
    font-size: 1rem;
    color: white;
    border-radius: 6px;
    background-color: red;
    border: none;
}
<button class="small">Test</button>
<button class="large">Test</button>

.small {
    padding: 0.1rem 0.6rem;
    font-size: 0.475rem;
    color: white;
    border-radius: calc(6px / 2); // This is how I tried to solve it
    background-color: red;
    border: none;
}

.large {
    padding: .5rem 3rem;
    font-size: 1rem;
    color: white;
    border-radius: 6px;
    background-color: red;
    border: none;
}
<button class="small">Test</button>
<button class="large">Test</button>


Solution

  • A visually consistent border-radius between buttons of different sizes, you can indeed use CSS's calc() function to adjust the border-radius proportionally to the size of the buttons.

    The smaller button will have a border-radius that appears scaled down appropriately.

    :root {
        --base-border-radius: 6px;
        --base-font-size: 1rem; /* This should match the font-size of the larger button */
    }
    
    .small {
        padding: 0.1rem 0.6rem;
        font-size: 0.475rem;
        color: white;
        border-radius: calc(var(--base-border-radius) * (0.475 / 1)); /* Adjusted based on the font-size ratio */
        background-color: red;
        border: none;
    }
    
    .large {
        padding: .5rem 3rem;
        font-size: 1rem;
        color: white;
        border-radius: var(--base-border-radius);
        background-color: red;
        border: none;
    }
    <button class="small">Test</button>
    <button class="large">Test</button>