How to create SASS such that classes with identical CSS are declared together with commas?

Viewed 53

Consider the SASS below.

@for $i from 1 through 5 {
.col-#{$i} {
position: relative;
}
}

It compiles to the following CSS.

.col-1 {
  position: relative;
}

.col-2 {
  position: relative;
}

.col-3 {
  position: relative;
}

.col-4 {
  position: relative;
}

.col-5 {
  position: relative;
}

But I would like it to compile like this.

.col-1,
.col-2,
.col-3,
.col-4,
.col-5 {
  position: relative;
}

How can this be done? I feel it should become the way I need with a slightly different syntax but I can't figure it out. Can anyone please help?

1 Answers

You can use @extend to do what you want :

%relative {
  position: relative;
}

@for $i from 1 through 5 {
  .col-#{$i} {
    @extend %relative;
  }
}

You will get :

.col-5, .col-4, .col-3, .col-2, .col-1 {
  position: relative;
}

Here is an explanation on how the @extend works. The % symbol is for placeholder selectors, it is useful if you don't want the extended selector (here %relative) to show up in your CSS.

Related