Search code examples
sassnestedampersand

SCSS: How to use two classes together with an ampersand?


I have some css rules to be applied for primary button, I did something like this:

.my-btn {
  &--primary {
     padding: 10px;
  }
}

Now I want same rules to be applied for a primary button with "sm" class, I can do something like this:

.my-btn {
  &--primary, &--primary.my-btn--sm  {
    padding: 10px;
  }
}

This is working for me. But I want to use "&" for "sm" as well, like this:

.my-btn {
  &--primary, &--primary.&--sm  {
    padding: 10px;
  }
}

Is it possible?


Solution

  • In this case, a solution could be use a variable:

    .my-btn {
      $this: &;
      &--primary, &--primary#{$this}--sm  {
        padding: 10px;
      }
    }
    

    Or use interpolation syntax

    .my-btn {
      &--primary, &--primary#{&}--sm  {
        padding: 10px;
      }
    }