Easier layout with margin-trim

Chris Coyier Chris Coyier on

Without the new property margin-trim, I’m forever doing :last-child { margin-block-end: 0; } and things like that to prevent an elements margin from combining with a parent elements padding to make too much space. The fact that we can avoid the extra awkward targeting and removal rule with this is great. I’ll stick by Coyier’s Padding Law:

When you add padding to a container element, add margin-trim in the same directions.

Wanna learn CSS from a course?

Frontend Masters logo

FYI, we have a full CSS learning path with multiple courses depending on how you want to approach it.

7-Day Free Trial

2 responses to “Easier layout with margin-trim”

  1. Carlos says:

    Either I’m missing something, or I don’t see any problem with continuing to use the classic next-sibling combinator to define margins.

    p + p {
    margin-block-start: 1lh;
    }

    I think if you limit yourself to working with margins in only one direction (usually the start direction, whether inline or block), there’s no problem. Can you think of any cases where margin-trim could be truly differential?

    • Chris Coyier says:

      p + p is cool. Limited to two paragraphs of course. You could go all lobotomized owl with it to make that more generally applicable (* + *). You could also toss a class name on the last element to remove that margin you don’t want. There are several ways to skin the cat here. I prefer the elegance and “keep it all on the same element” style of margin-trim.

      Tons of stuff in programming is just semantic sugar for something else and it comes down to understandability.

Leave a Reply to Carlos Cancel reply

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

Did you know?

Frontend Masters Donates to open source projects. $363,806 contributed to date.