Published at
Updated at
Reading time
2min

You probably know the problem of rounded boxes. You give a box a nice border-radius, everything looks good and all, and poof, if the box hits the viewport edges it looks terrible. I'm just cleaning up some tabs and I'm 100% certain that I'll come back to these snippets in the future. Maybe they're useful to you, too!

Here's Ahmad sharing his conditional border-radius solution:

.card {
  border-radius: clamp(0px, ((100vw - 4px) - 100%) * 9999, 8px);
}

This snippet should definitely come with a code comment because I doubt many people understand what's going on there. I'm not sure I do, even...

Here's Temani's solution:

.box {
  border-radius: calc(sign(100cqi - 100%)*2rem);
}

This is a little better but yeah... Still not very readable.

And here's Una's approach using the new CSS functions:

/* Conditionally apply a radius until you are (default: 4px, or specify second argument) from the edge of your screen */
@function --conditional-radius(--radius, --edge-dist: 4px) {
  result: clamp(0px, ((100vw - var(--edge-dist)) - 100%) * 1e5, var(--radius));
}

/* usage */
.box {
  /*  1rem border radius, default (4px) distance  */
  border-radius: --conditional-radius(1rem);
}

.box-2 {
  /*  1rem border radius, right at the edge (0px distance)  */
  border-radius: --conditional-radius(1rem, 0px);
}

If you look closely, you might discover that it's basically Ahmad's approach above wrapped in a CSS function (--conditional-radius), and I think this makes this CSS so much better. Bring in the complicated CSS once, but hide all its complexity. Nice nice!

If you enjoyed this article...

Join 6.2k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles