prograils
prograils

Reputation: 2376

SCSS: How to concatenate rules with the same style?

This SCSS code

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

generates such CSS output:

.style-1 {
  position: relative;
}    

.style-2 {
  position: relative;
}

And I want it to be such:

.style-1, .style-2 {
  position: relative;
}    

How to do it using a cycle in SCSS?

Upvotes: 3

Views: 895

Answers (2)

Robert Wade
Robert Wade

Reputation: 5003

Slightly different approach, but you can accomplish this with a SASS list:

/* SASS Input */    
$numbers: "1","2","3","4","5";
$selector: ();

@each $num in $numbers {
    $selector: append($selector, unquote('.style-#{$num}'), 'comma');
}

#{$selector} {
  position:relative;
}

/* CSS Output */
.style-1, .style-2, .style-3, .style-4, .style-5 {
    position: relative;
}

Upvotes: 2

3rdthemagical
3rdthemagical

Reputation: 5350

You can use placeholder selector to group rules.

Sass supports a special type of selector called a “placeholder selector”. These look like class and id selectors, except the # or . is replaced by %. They’re meant to be used with the @extend directive. On their own, without any use of @extend, rulesets that use placeholder selectors will not be rendered to CSS.

Sassmeister demo.

Scss:

%common {
  position: relative;
}

@for $i from 1 through 2 {
  .style-#{$i} { 
    @extend %common;
  }
}

Css output:

.style-1, .style-2 {
  position: relative;
}

Upvotes: 2

Related Questions