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

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? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.