I was reviewing some old code and came across a block for a grid setup that looked like this:
.grid-100 {
width: 100%;
}
.grid-95 {
width: 95%;
}
.grid-90 {
width: 90%;
}
It struck me that this must’ve been code brought in from some pre-made CSS grid framework because the code was quite verbose, nearly repetitive. I noticed the pattern and figured it could be cleaned up quite a bit using Sass variables and the @for
directive. The original _grid.scss
partial was 94 lines of code. I was able to shrink it down to 36 lines using the @for
directive. That’s over 60% reduction!
Most of the original code consisted of a class name whose only rule was a width specification—similar to what you find in any grid framework—and the only things that changed from rule to rule were the class names and the values assigned to the width property. So I knew I could use the Sass @for
directive (and a little interpolation) to create all of the classes I needed, and a variable (with a simple math calculation) to replace the values for each new class.
Here’s the code I ended up with:
@for $i from 1 through 20 {
.grid-#{($i * 5)} {
width: ($i * 5%);
}
}
It reads: for each item from 1 through 20 create a class name prefixed with ‘grid-‘ followed by the product of the item number times 5 and set the width property of the class to the product of the item number times 5%.
With this one refactored block of code, my Sass file instantly shrunk in half and became significantly easier to read, all without changing the CSS output. And that’s exactly what pre-processors are meant to do—make your code easier to maintain without affecting client-side behavior.
Of course, this was a super simple exercise/refactoring. You can do so much more with the Sass @for
directive.
Here’s another quick five-line example that creates gradient-colored text classes:
@for $i from 1 through 5 {
.color-#{($i)} {
color: (adjust-hue(#ff0000,($i*10)));
}
}
Again, super simple. (Both of these gists can be downloaded from Github.)
I encourage you to bring the code over to SassMeister or CodePen and see what else you can do with it. Let me know if you come up with anything cool!
Leave a Reply