Quick­ly build a sim­ple grid with Sass

Publisher: TJ Fogarty

Modified: 2018-03-13

All you need are some vari­ables and loops. Grant­ed, some may argue for read­abil­i­ty, but as long as what you’re doing is well doc­u­ment­ed, it can save you a lot of time. Espe­cial­ly if you want to add/​remove breakpoints.

The end result should be a sim­ple class list that is respon­si­ble for the width of your col­umn. I’m using a seper­ate class to take care of floats and padding.

For my pur­pos­es, I’m using .layout__item and .g-1-12, .g-2-12… etc

.layout__item will con­tain the following:

.layout__item {
    padding-left: 15px;
    padding-right: 15px;
    float: left;
}

Start­ing off, I need a for­mu­la for cal­cu­lat­ing width based off a frac­tion of how many columns I want. 

Say I want­ed a col­umn to extend 412 of the page, I’d use:

(4 / 12) * 100%

In Sass, this would return 33.33333%. Hap­py days, so let’s keep that in a function.

@function percentage-width($span, $columns) {
  @return ($span / $columns) * 100%;
}

I’m then going to keep my colums in a variable.

$grid-column: 12;

Next, I’m going to use a for loop to iter­ate through my num­ber of columns, and use the percentage-width function.

@for $i from 1 through $grid-columns {
  .u-#{$i}-#{$grid-columns} {
    width: percentage-width($i, $grid-columns);
  }
}

This yields the following:

.u-1-12 {
  width: 8.33333%; }

.u-2-12 {
  width: 16.66667%; }

.u-3-12 {
  width: 25%; }

etc…


So what about break­points? The above exam­ple would sure­ly serve well as a mobile-first start­ing point.

Let’s throw in anoth­er vari­able, a map:

$grid-breakpoints: (
  medium: 768px,
  large: 960px
);

We can use the above loop again, but mod­i­fy it slight­ly to include medi­um and large in the class name.

// Loop breakpoints to generate screen-specific grids
@each $key, $val in $grid-breakpoints {
  @media (min-width: #{$val}) {
    @for $i from 1 through $grid-columns {
      .u-#{$i}-#{$grid-columns}--#{$key} {
        width: percentage-width($i, $grid-columns);
      }
    }
  }
}

It’s the same loop, but repeat­ed for every break­point defined in $grid-breakpoints, result­ing in:

@media (min-width: 768px) {
  .u-1-12--medium {
    width: 8.33333%; }
  .u-2-12--medium {
    width: 16.66667%; }

And so on.

You can grab the source and see a small exam­ple on Code­Pen.

See the Pen Sim­ple grid with Sass by T.J. Fog­a­r­ty (@tjFogarty) on Code­Pen.