#132: A Quick Useful Case for Sass Math and Mixins

Avatar of Chris Coyier
Chris Coyier on (Updated on )

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

I had a little design situation come up where I was making a fluid grid of boxes with floats. I wanted to specify how many boxes across a row was very easily, and have them flush against both edges of the container. Not too difficult, as we know from not overthinking grids and using the right box-sizing, you can get four floated boxes in a row width 25% width – easy.

But what if you want to use margin between the boxes? Still totally possible, just requires some thinking. Say you want four in a row, you’ll need to figure out how much space you have left after all the margin is used. Because you don’t want margin on the last one in the row, that’s 3 margins:

100% - (3 * MARGIN)

3 is really “rows you want minus one”, so:

100% - ((ROWS - 1) * MARGIN)

Then you divide the space you have left by how many boxes you want on that like, so:

(100% - ((ROWS - 1) * MARGIN)) / ROWS

You could use Sass for that:

$numPerRow: 4;
$margin: 2%;

width: ((100% - (($numPerRow - 1) * $margin)) / $numPerRow);

Even better, we make that into a @mixin, so we can just call it whenever we need it:

@mixin rowMachine($numPerRow, $margin) {
  width: ((100% - (($numPerRow - 1) * $margin)) / $numPerRow);
  &:nth-child(n) {
    margin-bottom: $margin;
    margin-right: $margin;
  &:nth-child(#{$numPerRow}n) {
    margin-right: 0;
    margin-bottom: 0;

Watch the video to learn about that tricky bit with :nth-child

In the video, the bit in the beginning with the Jade loop you can learn more about here.

And here’s the Pen:

See the Pen Simple Technique for using Sass for Rows by Chris Coyier (@chriscoyier) on CodePen.