Just a quick article based on a post by Natalie 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;
}

Natalie 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.