Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain a class to an element with a parent selector in SASS [duplicate]

Tags:

sass

I'm trying to do the following with SASS (scss).

.class {
  // Base class styles

  a.& {
    // Additions for when applied to a link
  }
}

But I get a compiler error:

Invalid CSS after "a.": expected class name, was "&"

Any ideas how to achieve this? Currently I just break out of nesting, but it's sub optimal for my case.

Thanks!

like image 418
krulik Avatar asked Oct 28 '25 08:10

krulik


1 Answers

As of SASS 3.4, you can use the @at-root directive in order to scope the selector to the root.

In addition, you will also need to interpolate the parent selector, &, like: a#{&}:

.class {
  // Base class styles

  @at-root a#{&} {
    color: #000;
  }
}

Which would compile to:

a.class {
  color: #000;
}

It's worth mentioning that you can nest multiple elements under @at-root:

.class {
  // Base class styles

  @at-root {
    a#{&} {
      color: #f00;
    }
    p#{&} {
      float: left;
    }
  }
}

Which would compile to:

a.class {
  color: #f00;
}
p.class {
  float: left;
}
like image 197
Josh Crozier Avatar answered Oct 31 '25 11:10

Josh Crozier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!