Search code examples
csssass

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


I'm working with the SCSS syntax of SASS to create a dynamic grid system but I've hit a snag.

I'm trying to make the grid system completely dynamic like this:

$columns: 12;

then I create the columns like this:

@mixin col-x {
  @for $i from 1 through $columns {
  .col-#{$i} { width: $column-size * $i; }
  }
}

Which outputs:

.col-1 {
    width: 4.16667%;
  }

.col-2 {
    width: 8.33333%;
}
etc...

This works well but what I want to do next is dynamically generate a long list of column classes separated by commas based on the number of $columns chosen - e.g I want it to look like this:

.col-1,
.col-2,
.col-3,
.col-4,
 etc... {
float: left;
}

I've tired this:

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

but the output is this:

.col-1 {
  float: left;
}
.col-2 {
  float: left;
}
etc...

I'm a little stuck on the logic here as well as the SCSS syntax required to create something like this.

Does anyone have any ideas?


Solution

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