Jan's Development Microblog
Go back to blog overview

I created my own margin-trim mixin for SASS/SCSS

— by in CSS
Read time: 3 min

I needed the CSS feature margin-trim, but it is not really supported yet, so I built my own SASS mixins for it. So it will work cross browser.

I created my own margin-trim mixin for SASS/SCSS

A little while back, I was working on one of my projects and needed to get rid of whitespace at the top and bottom of a content container. I remembered that margin-trim was introduced a long while back, and it was the solution I needed for my problem. However, there was one little problem: the browser support for margin-trim was almost non-existent. This CSS feature was introduced to Safari in March 2023. So far, other browsers haven't added support for it yet. So, as I wanted to keep my SASS code clean, I opted to create my own SASS mixins. Of course, I could've chosen the Tailwind way, by writing some CSS code like below and adding this class to every single HTML element where needed.

​​.margin-trim {
> :first-child {
margin-block-start: 0;
}
> :last-child {
margin-block-end: 0;
}
}

I'm not really a fan of making a mess due to class spamming with hundreds of classes to style a simple container. Since the project I am currently working on is using SASS, there was a better option: creating my own SASS mixins to use margin-trim. This way, I only have to write the code once and include the SASS mixins wherever I need them, mostly on text containers. I always try to code using the DRY method (Don't Repeat Yourself), so this method fits perfectly with my approach.

Here is the SASS mixin I came up with. If margin-trim is supported by the browser, it will apply the first rule; otherwise, it will fall back to a method that works in all browsers.

@mixin margin-trim-block() {

@supports (margin-trim: block) {
margin-trim: block;
  }

@supports not (margin-trim: block) {
> :first-child {
margin-block-start: 0;
}

> :last-child {
margin-block-end: 0;
}
}
}

I have used this SASS mixin for a little while now, and I still like it. I hope you will find some use for it. I cannot wait until margin-trim is supported by all browsers.