Greetings, inspector! If you wanna see more, check my Github: mococa 😏

author avatarLuiz Felipe Moureau

08/06/2023/Articles

Margin-trim as a best practice?

It’s not every day there is a new “best practice” for CSS, since it’s such a huge, ubiquitous, and highly used language. But here’s one, maybe?
Margin-trim as a best practice?

If you have both padding and margin in the same direction, the amount of space in that direction is their combined total. My thinking is that it’s quite rare that the space you actually want is that combined total. It’s probably just the padding. The margin is likely there for child elements pushing each other away.

Doing this looks like:

.card {
  padding: 1rem;
  margin-trim: block;
}

.nav {
  display: flex;
  padding: 0.25rem 1rem;
  margin-trim: inline;
}

In the example above, because there is padding in the block direction, margin-trim is also used in that direction. And there are elements with padding in those directions, so it’s cut off. Nice. No more ughgk this again I guess I’ll try to fight it with some kind of :last-child/:first-child margin-removing thing that I hope is specific enough to work. This solves the extra space problem from the parent level.

You could think of using flexbox and gap, but it’s just not 100% supported accross every browser.

I couldn’t see a keyword value that would margin-trim in all directions 🤷. But I guess I can kinda the reasoning, like in that example above if the margin was trimmed in the inline-end direction only on the last paragraph it would be like… why? It wouldn’t be doing the same useful thing. It would have to be more heuristically built, trimming margin from any element that butts against the inline-end, but I don’t think that’s how it works.

If margin-trim had come out before flexbox and grid layout, it would have been huge. It’s such a little annoyance that we need to select the last element somehow and remove the flow-direction margin, lest be left with more space than we want. Both flexbox and grid have gap, which is beloved for this very reason. I just want to space things out between elements.

This makes me wonder if there is a generic way to express this idea. Perhaps even something that you could chuck in a reset stylesheet? The most modern thing I can think of would be a (range-style?) style query that checks if it needs to apply margin-trim based on the existence of padding in that direction:

Luiz Felipe Moureau

Fullstack developer at Space.game