One of the interesting (but annoying) things about CSS is the background of children’s elements can bleed out of the border radius of the parent element. Here’s an example of a card with an inner element. If the inner element is given a background, it can bleed out of the card’s border.
The easiest way to resolve this problem is to add overflow: hidden
to the card element. I’m sure that’s the go-to solution most of us reach for when this happens.
But doing this creates a new problem — content outside the card element gets clipped off — so you can’t use negative margins or position: absolute
to shift the children’s content out of the card.
There is a slightly more tedious — but more effective — way to prevent a child’s background from bleeding out of the parent’s border-radius
. And that is to add the same border-radius
to the child element.
The easiest way to do this is allowing the child to inherit
the parent’s border-radius
:
.child {
border-radius: inherit;
}
If the border-radius
shorthand is too much, you can still inherit the radius for each of the four corners on a case-by-case basis:
.child {
border-top-left-radius: inherit;
border-top-right-radius: inherit;
border-bottom-left-radius: inherit;
border-bottom-right-radius: inherit;
}
Or, for those of you who’re willing to use logical properties, here’s the equivalent. (For an easier way to understand logical properties, replace top and left
with start
, and bottom
and right
with end
.)
.child {
border-start-start-radius: inherit;
border-top-end-radius: inherit;
border-end-start-radius: inherit;
border-end-end-radius: inherit;
}
Can’t we just apply a background on the card?
If you have a background
directly on the .card
that contains the border-radius
, you will achieve the same effect. So, why not?
Well, sometimes you can’t do that. One situation is when you have a .card
that’s split into two, and only one part is colored in.
So, why should we do this?
Peace of mind is probably the best reason. At the very least, you know you won’t be creating problems down the road with the radius manipulation solution.
This pattern is going to be especially helpful when CSS Anchor Positioning gains full support. I expect that would become the norm popover positioning soon in about 1-2 years.
That said, for popovers, I personally prefer to move the popover content out of the document flow and into the <body>
element as a direct descendant. By doing this, I prevent overflow: hidden
from cutting off any of my popovers when I use anchor positioning.
Solving Background Overflow With Inherited Border Radii originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
0 Comments