Search code examples
sasscompass-sasscompass

SASS Mixin Rewrite & (ampersand)


I'm trying to write a mixin that will modify the parent selector on output. The idea is that in cases where a mixin is called, the parent selector will need to have a string replacement done on it. I have most of this working, but I can't figure out how to swallow the &.

.test {
  @include alt_parent() {
    content: 'test';
  }
}

The mixin is something like this:

@mixin alt_parent() {
  #{str-replace(unquote("#{selector_append(&)}"), "s", "x")} {
    @content;
  }
}

I have the string replacement working, so that isn't the problem. What I get is this (and I understand why):

.test .text {
  content: 'test';
}

What I want is this:

.text {
  content: 'test';
}

Solution

  • You have to use the @at-root directive to defeat the automatic inclusion of the selectors represented by &.

    http://alwaystwisted.com/articles/2014-03-08-using-sass-33s-at-root-for-piece-of-mind

    @mixin alt_parent($parent) {
        @at-root {
            #{str-replace(unquote("#{selector_append(&)}"), "s", "x")} {
                @content;
            }
        }
    }