Search code examples
csssass

Grouping Sass Selectors When Using @for


I have a group of heading levels (1 through 6). I am using a @for loop but I can't seem to work out how to group them as one instead of individually.

This is the @for loop I'm using:

@for $i from 1 through 6 {
   h#{$i},
   .h#{$i} {
      margin-bottom: $headings-margin-bottom;
      line-height: $headings-line-height;
      font-weight: $headings-font-weight;
      font-family: $headings-font-family;
   }
}

Here's what I am expecting:

h1,
h2,
h3,
h4,
h5,
h6 {
   /* styles */
}

Here's what is getting compiled:

h1 {
   /* styles */
}

h2 {
   /* styles */
}

h3 {
   /* styles */
}

...

Solution

  • You can use @extend to join the selectors:

    %myStyle {
      margin-bottom: $headings-margin-bottom;
      line-height: $headings-line-height;
      font-weight: $headings-font-weight;
      font-family: $headings-font-family;
    }
    
    @for $i from 1 through 6 {
       h#{$i}, .h#{$i} {
          @extend %myStyle;
       }
    }
    

    The symbol % is a placeholder selector, you can use it so myStyle will not show up in the compiled CSS.