Spacing Classes : Whats the big idea?!

What the hell are spacing classes?!.

Well…they’re exactly that.

Defined classes used for allocating margin or padding to elements. The goal is to separate layout from normal styles, and being able to utilise classes for padding or margin makes for consistant spacing, and a smaller CSS file.

We’ve all styled an element with a combination of style and layout, like the following:

.title {
    background: #336633;
    color: #fff;
    font-size: 36px;
    line-height: 45px;
    margin: 20px 10px; /* Layout */
    padding: 10px; /* Layout */
    text-transform: uppercase;
}

But if you’re working to a specific grid and/or baseline, you’ll no doubt be declaring these same layout properties all over the place.

Enter spacing classes.

I wrote a spacing class mixin that generates a collection of class names consisting of a combination of layout properties and a size.

For instance, “padding” classes start with “pad”, “margin” classes start with “inset” and “negative margin” classes start with “offset”.

The mixin iterates over the number of names in the list, multiplying the baseline value by the current position in the list and assigns the result to specific name in the list. So small, becomes 10px, normal becomes 20px, medium becomes 30px and large becomes 40px. So we’re left with a series of names such as pad-normal, inset-large, offset-medium, etc.

.pad-normal {
    padding: 20px;
}

.inset-normal {
    margin: 20px;
}

.offset-normal {
    margin: 20px;
}

These classes allow you ditch these recurring layout properties from your styles, and just apply the spacing class to the element.

<h1 class="inset-normal">I can't believe I ate the whole thing</h1>

Another combination included in the mixin is whether you want the render the layout horizontally or vertically.

.pad-vert-normal {
    padding-top: 20px;
    padding-bottom: 20px;
}

.inset-hoz-normal {
    margin-right: 20px;
    margin-left: 20px;
}

.pad-vert-normal-small {
    padding-top: 20px;
    padding-bottom: 10px;
}

.inset-hoz-normal-large {
    margin-right: 20px;
    margin-left: 40px;
}

If the default settings don’t suit your layout, or perhaps there aren’t enough options for you, just pass through a new base value and list.

@include spacing-classes($base: 5px, $list: big bigger biggerer evenbiggerer biggest);

/* generates the follwoing */

.pad-big {
    padding: 5px;
}

.pad-bigger {
    padding: 10px;
}

.pad-biggerer {
    padding: 15px;
}

.pad-evenbiggerer {
    padding: 20px;
}

.pad-biggest {
    padding: 25px;
}

Stitchcss

For those of you not aware of Stitchcss, Stitch is a CSS patterns library developed by @anthonyshort, built with Sass. The library consists of a heap of mixins for popular design patterns that will help you speed up your development process. So I urge you to check it out.