Phil Kurth
/ Tips /

A utility CSS class for removing margins on first and last child elements.

Last updated • 1 October 2019

I’ve recently been developing sites using a utility-based approach with my CSS and I’m kinda loving the flexibility that comes with this paradigm.

One particularly useful class I seem to use a lot is one that removes margins from the first and last elements within a container. I use this a lot because I tend to prefer to use padding to control the inner spacing in a box and margins can often get in the way of this.

The straight-up CSS approach


.m-0-first-last > :first-child {
    margin-top: 0;
}

.m-0-first-last > :last-child {
    margin-bottom: 0;
}

Using SCSS for a little more flexibility

This is how I work it as I’m almost always working with SCSS. By having the additional mixin, I’m able to pull the approach into any other existing classes where adding a utility class isn’t feasible.


// Define a mixin so we can use this anywhere we need it
@mixin first_last_marginless() {
    > :first-child {
        margin-top: 0;
    }

    > :last-child {
        margin-bottom: 0;
    }
}

// Set up a utility class using the mixin
.m-0-first-last {
    @include first_last_marginless;
}

Got a project in mind?
Let's talk.

Every project starts with a conversation about what you need. You hear back the same or next business day. If I'm not the right fit, I'll say so. If I am, you get a fixed quote before any work starts.

Phil Kurth, web designer and developer in Geelong