Sass ampersand, select immmediate parent?

You need to wrap @at-root content in {}

.wrapper {
    h1 {
        @at-root {
           .wrapper .active h1 {
                color: red;
           }
        }
    }
}

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;
}

As of this writing, there is no Sass selector for the direct parent instead of the root parent of an element. There is & which (as you know) selects the root parent. There are also % placeholder selectors which hides a rule until it's been extended.

Sass is open-sourced, so you could contribute a new "direct parent" selector.

Tags:

Sass