Loops and Mixins with Sass
Recently I have been working on a project that requires category specific styles across 8 different categories. Nothing too complicated, mostly just setting some hover colors on a per category basis.
To start I had declared a variable with a list of category slugs as they would be added to the body by WordPress. I also declared variable with a list of the colors associated with each category in matching order. I then created a mixin that accepts two parameters, $categoryName and $color. It uses $categoryName as the class selector for the page specific body class and sets the color in a couple of different places.
I then wrote a @for loop with an increment starting at 1 (for whatever reason Sass lists are indexed at 1 and not 0) through the total length of the category list. Two variables set inside the loop select a category and a color based on the increment, and each are passed to the mixin. Away we go.
Some benefits of doing it this way:
- The base styles took around 22 lines of Sass, which would have come out to around 176 lines for all of the categories. This method took around 30 lines total, making the file a lot easier to work with down the road.
- Basing the loop on the length of the categories list allows us to add a category and color without too much trouble.
- The computer does some of the work for you.
High fives all around!
Hey, like this post? Why not share it with a buddy?Tweet