Sass ampersand, select immmediate parent?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)