Conditional Border Radius In CSS

Ahmad Shadeed recently spotted this declaration in Facebook’s CSS:

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

It’s a really interesting piece of code, which acts as a toggle to only show rounded corners in case the element does not entirely span the viewport width.

You can see it in action in this (resizable) demo:

See the Pen
Border radius / FB
by Ahmad Shadeed (@shadeed)
on CodePen.

That calc((100vw - 4px - 100%) * 9999) in the code will either yield a very big positive number or very big negative one. You might recall this technique from the Flexbox Holy Albatross. Combined with min and max, the result will be one of 0px or 8px.

The 4px in the equation acts as an offset to take into account: the border-radius will only be gone when there’s less than 4px (2px on each side) available. In the demo below I’ve animated the width and adjusted the offset to be 40px (thus 20px on each side).

See the Pen
Border radius / FB
by Bramus (@bramus)
on CodePen.

On his blog, Ahmad explains (and illustrates) the math in more detail: Conditional Border Radius In CSS →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.