Search code examples
sassnode-sass

Conditionally output a part of SCSS rule selector


I would like to specify an additional default shortcut class to a set of classes, similarly to that

@each $pos, $some-css-rules in ("left": ..., "right": ..., ...) {

  @if $pos == "left" {
    .block,
  }

  .block-#($pos) {
     ...
  }
}

that would be outputted as

.block,
.block-left {
  ...
}

.block-right {
  ...
}

However, it will stumble over .block, syntax error.

.block-left cannot be replaced here with .block.left because $pos will collide with existing classes (.left, etc).

I would prefer to avoid .block { @extend .block-left } if possible, there is a considerable amount of similar rules that will gain a lot of WET code this way.

Is there a way to conditionally output a part of rule selector? How can both SCSS and CSS be kept DRY in a pattern like that?


Solution

  • I'm not sure if I understand the question but I achieve the output CSS based on your code. I put the @if directive inside the selector to compare with $pos variable. Here is my code:

    SASS

    @each $pos, $some-css-rules in ("left": red, "right": blue) {
      .block-#{$pos} {
      @if $pos == "left" {
        @at-root .block, &{
        color:$some-css-rules;
        }
      } 
        @else{
          color:$some-css-rules;
        }
      }
    }
    

    Output

    .block, .block-left {
      color: red;
    }
    
    .block-right {
      color: blue;
    }