CSS utility class for full bleed child inside padded parent
Say you have a
Card component with 20px padding and you need a child element to span from edge to edge, going over padding. Something like this:
To avoid modifying parent, we can apply a negative margin on the child element to make it span outside the padded area.
margin-left: -20px; margin-right: -20px;
That solves it but it makes for tight coupling since we need to know the exact padding value of the parent and match it.
We can avoid this by using an extremly large margin value (like -9999rem) and combining it with equal padding value to make sure content stays in place.
margin: -9999rem; padding: 9999rem;
Cool thing is, the original 20px padding from the parent will still be respected! The only constraint is, we have to apply
overflow: hidden on the parent to avoid child element stretching across the full screen.
I found this solution useful enough to get it’s own little utility class:
Note that I explicitly use
*-right properties instead of
padding shorthands to allow vertical padding to be inherited or set independently.