Using Sass' @each to create DRY selectors

Just a quick article based on a post by Nathan Weizenbaum in the Sass Google Group on how to use the @each directive to create selectors.

Someone there was looking for a way to use @each while keeping a DRY output. I haven't used @each in this way yet (I usually use it when the properties change for each key, like when going over an array of social media networks), but I can imagine there are use cases.

Normally, this code:

@each $brand in volkswagen, bmw, chrysler
  .car-#{$brand}
    color: silver

Would result in:

.car-volkswagen {
  color: silver;
}

.car-bmw {
  color: silver;
}

.car-chrysler {
  color: silver;
}

But what if you want DRY'er code and want to combine the selectors, like:

.car-volkswagen,
.car-bmw,
.car-chrysler {
  color: silver;
}

Nathan suggests this "hacky" approach:

$selectors: ()

@each $brand in volkwswagen, bmw, chrysler
  $selectors: $selectors, unquote(".car-#{$brand}")

#{$selectors}
  color: silver

Maybe not the most elegant solution, but depending on the situation it may be better than the alternative. I don't think I'll be using it, but hey, it's a clever solution.

May I recommend these resources?

If you're a back-end developer having to work with front-end code, I suggest checking out Modular Front-End and Front-End Talk. And you should follow me on Twitter, duh.

blog comments powered by Disqus