Search code examples
cssif-statementsassparent

SASS: Using the parent reference (&) inside and @if ... @else structure. & picks up else instead of parent


I'm using the &: select inside a SASS @if block inside a mixin.

@mixin mixin-name {
   @if (condition) {
        .....
   } else {
        &:nth-of-type(...) {}
   }
}

The &:Nth-of-type is the outermost actual selector inside the mixin. In my code, I use it this way:

aside {
    @include mixin-name;
}

I'm expecting this in the CSS output:

aside:nth-of-type() {}

Instead, I get this:

aside else:nth-of-type() {}

Clearly SASS is picking up the else as the "parent" instead of the aside. The old mixin included the aside element within the mixin, but I wanted to make it more flexible, to use it with any selector.

My current solution is to pass the selector into the mixin as variable and use it this way:

#{$var} {
    &:nth-of-type() {}
}

This works, but it seems like a bug that the & should pick up a piece of code instead of the actual selector. Anyone have a more elegant solution?


Solution

  • Use @else. You can check the full documentation here: SASS Docs

    Basically, SASS is thinking that else is a CSS keyword/identifier. It needs to be prefixed with the @.

    Ie, your code would become:

    @mixin mixin-name {
       @if (condition) {
            .....
       } @else {
            &:nth-of-type(...) {}
       }
    }