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.
We don’t want rounded corners when the window is narrow enough for the cards to span the entire viewport, so we use the “Fab Four” technique to collapse the border-radius to zero conditionally. https://t.co/QrGkjmVInE
— Frank Yan (@frankyan) October 3, 2021
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 →
💡 You can also use this with the container relative 100qw
, which matches the container’s width
. See this CodePen demo.