A interesting (but annoying) feature of CSS is that the background of the child element may overflow the rounded border of the parent element. For example, a card containing internal elements, if the internal element is set, its background may overflow the card's border.
Usually the easiest way to solve this problem is to add overflow: hidden
attributes to the card element. I believe this is the first solution that most people think of when they encounter this situation.
However, doing this creates a new problem - the content outside the card element is cut out - so it is impossible to use negative margins or position: absolute
to move the contents of the child element out of the card.
There is a slightly cumbersome but more effective way to prevent the background of the child element from overflowing the parent element's rounded border, which is to add the same rounded border to the child element.
The easiest way is to allow the child element to inherit the rounded border of the parent element:
.child { border-radius: inherit; }
If the abbreviation of border-radius
is too long, you can still inherit the rounded corner radius of the four corners according to the situation:
.child { border-top-left-radius: inherit; border-top-right-radius: inherit; border-bottom-left-radius: inherit; border-bottom-right-radius: inherit; }
Or, for those willing to use logical properties, here is the equivalent code. (For easier understanding of logical properties, replace top
and left
with start
and bottom
and right
with end
.)
.child { border-start-start-radius: inherit; border-start-end-radius: inherit; border-end-start-radius: inherit; border-end-end-radius: inherit; }
If the .card
element itself contains border-radius
and sets the background directly, the same effect can be achieved. So, why not do this?
Well, sometimes you can't do it. For example, when your .card
element is divided into two parts, with only a part of it colored.
Standby may be the best reason. At least, you know you won't create problems later when using the rounded radius adjustment scheme.
This mode is especially useful when CSS anchor positioning is fully supported. I expect this will soon become the norm for pop-up positioning in 1-2 years.
That is, for pop-ups, I personally prefer to move the pop-up content out of the document stream and put it into the element as a direct child element. By doing this, I can prevent
overflow: hidden
from cropping out any popups when using anchor positioning.
The above is the detailed content of Solving Background Overflow With Inherited Border Radii. For more information, please follow other related articles on the PHP Chinese website!