How to dynamically generate a list of classes with commas separating them?

I think you may want to take a look at @extend. If you set that up something like:

$columns: 12;

%float-styles {
  float: left;
}

@mixin col-x-list {
  @for $i from 1 through $columns {
      .col-#{$i}-m { @extend %float-styles; }
  }
}

@include col-x-list;

It should render in your css file as:

.col-1-m, .col-2-m, .col-3-m, .col-4-m, .col-5-m, .col-6-m, .col-7-m, .col-8-m, .col-9-m, .col-10-m, .col-11-m, .col-12-m {
  float: left;
}

@extend in the docs.


thnx to @davidtheclark here is a more generic version:

@mixin attr-x($attr, $attr-count: 10, $attr-steps: 10, $unit: '%') {
    $attr-list: null;
    @for $i from 1 through $attr-count {
        $attr-value: $attr-steps * $i;

        .#{$attr}#{$attr-value} {
            #{$attr}: #{$attr-value}#{$unit};
        }

        $attr-list: append($attr-list, unquote(".#{$attr}-#{$attr-value}"), comma);
    }

    #{$attr-list} {
        //append style to all classes
    }
}

Use it like this:

@include attr-x('margin-left', 6, 5, 'px');
//or
@include attr-x('width');

The result looks like this:

.margin-left5 {
  margin-left: 5px; }

.margin-left10 {
  margin-left: 10px; }

...

.margin-left30 {
  margin-left: 30px; }

.width10 {
  width: 10%; }

.width20 {
  width: 20%; }

...

.width100 {
  width: 100%; }

There's also a way to do what your question is specifically asking for: generate (and use) a list of classes with commas separating them. D.Alexander's response totally works in your situation, but I'm posting this alternative in case there's another use case for someone looking at this question.

Here's a Pen demonstrating: http://codepen.io/davidtheclark/pen/cvrxq

Basically, you can use Sass functions to achieve what you want. Specifically, I'm using append to add classes to my list, separated by commas, and unquote to avoid compilation conflicts with the period in the classnames.

So my mixin ends up looking like this:

@mixin col-x {
  $col-list: null;
  @for $i from 1 through $columns {
    .col-#{$i} {
      width: $column-size * $i;
    }
   $col-list: append($col-list, unquote(".col-#{$i}"), comma);
  }
  #{$col-list} {
    float: left;
  }
}

Tags:

Css

Sass