Sass ampersand, select immmediate parent

sass

Is there a way in Sass to use the ampersand to select the immediate parent, rather than the parent selector of the entire group? For example:

.wrapper{
    background-color: $colour_nav_bg;
    h1{
        color: $colour_inactive;
        .active &{
            color: red;
        }
    }
}

compiles to:

.wrapper h1{
    color: grey;
}

.active .wrapper h1{
    color: red
}

but what I actually want is:

.wrapper .active h1{
    color: red;
}

Is the only option to write the SCSS like so?

.wrapper{
    background-color: $colour_nav_bg;
    h1{
        color: $colour_inactive;
    }
    .active h1{
        color: red;
    }
}

The HTML looks like this:

<ul class="wrapper">
    <li class="active">
        <h1>blah</h1>
    </li>
</ul>

Best Answer

You can work around this today with a mixin like this one:

@mixin if-direct-parent($parent-selector) {
  $current-sequences: &;
  $new-sequences: ();

  @each $sequence in $current-sequences {
    $current-selector: nth($sequence, -1);
    $prepended-selector: join($parent-selector, $current-selector);
    $new-sequence: set-nth($sequence, -1, $prepended-selector);
    $new-sequences: append($new-sequences, $new-sequence, comma);
  }

  @at-root #{$new-sequences} {
    @content;
  }
}

Since the & is essentially a list of lists, you can use list functions (nth, set-nth, join and append) to create the selector sequence you want. Then use @at-root to output the new selector at root-level. Here's how you'd use it:

.grandparent-1,
.grandparent-2 {
  color: red;

  .child {
    color: blue;

    @include if-direct-parent('.parent') {
      color: green;
    }
  }
}

Which will output:

.grandparent-1,
.grandparent-2 {
  color: red;
}
.grandparent-1 .child,
.grandparent-2 .child {
  color: blue;
}
.grandparent-1 .parent .child, .grandparent-2 .parent .child {
  color: green;
}
Related Topic