4

In Sass, we all use to do things like this:

button {
  @extend %button;

  &.previous,
  &.next {
    background: blue;
  }
}

Today, I need the exact opposite: check the element type inside a class selector. Here's my first attempt, which I expected to work:

.previous,
.next {
  @extend %button;

  &span {
    opacity: .3;
  }
}

Unfortunately, this outputs selectors like .previousspan and .nextspan. I tried to use span&, or interpolation as I highly suppose it could solve my problem, but I'm stuck.

Any idea?

Note: I could obviously put this span selector outside (and that's what I've done to get it to work), but this is not the point of my question. I'm really searching for the right way to do it, thanks.

zessx
  • 68,042
  • 28
  • 135
  • 158
  • 1
    Then you're looking for this question: http://stackoverflow.com/questions/26051712/in-sass-how-to-reference-two-parent-classes-with-ampersand-to-compound-with-an – cimmanon Feb 01 '16 at 13:36
  • Perfect, many thanks! Have you got a way to change the duplicate, to redirect on the right answer? – zessx Feb 01 '16 at 13:38

1 Answers1

3

With the latest versions of Sass, you could implement it like so:

.class {
  @at-root {
    div#{&} {
      opacity: .3;
    }
  }
}

@at-root, will make sure to nullify the "scope" of the selector, while still giving you access to the ampersand variable.

However it's usually a better idea to not target tag names at all. Sementically speaking.

GMchris
  • 5,439
  • 4
  • 22
  • 40
  • I tried this, but for some reason it'll output `.previous span.previous`, which is not correct. And I agree with you about targeting tag names, I'm overriding some CMS styles, and have no control over HTML structure. – zessx Feb 01 '16 at 11:04
  • Won't work either, because there're two class selectors. It'll output `span.previous, .next {}` instead of `span.previous, span.next {}`. Anyway, I discovered that `@at-root` could be used as a block wrapper! – zessx Feb 01 '16 at 11:14