0

Is there a way with Sass to have nested elements without explicit class names?

To take something like this:

.foo {color: blue;}
p.foo {background: yellow;}
span.foo {background: red;}

<p class="foo">Styled paragraph text</p>
<span class="foo">Styled span text</span>

And turn it into something like:

.foo {
  color: blue;  

  & p {
    background: yellow;
  }

  & span {
    background: red;
  }

}

fiddle

5
  • 1
    @cimmanon similar/same question - has better title. mine is likely formatted and posed better
    – justinw
    Apr 16, 2015 at 18:53
  • 1
    What does that have to do with anything? A duplicate is a duplicate, and duplicates should be closed. The other close voter had no idea what you were even asking, so it clearly wasn't phrased as well as you think it is.
    – cimmanon
    Apr 16, 2015 at 18:56
  • 2
    @cimmanon The question was clear. If all duplicates should be closed, why don't you close the linked duplicate as a duplicate of the "better duplicate"..? Apr 16, 2015 at 19:00
  • 1
    @JoshCrozier Why are you reopening duplicates?
    – cimmanon
    Feb 9, 2016 at 20:40
  • @cimmanon You closed it as a dupe of this originally, so I was just trying to find this one instead.. also, I just happened to stumble upon this question when searching through other related duplicates... are you fine with that? Feb 9, 2016 at 20:42

1 Answer 1

4

According to this GitHub issue, you can use the following as of SASS v3.3.0:

.foo {
  color: blue;  
  @at-root {
    p#{&} {
      background: yellow;
    }
    span#{&} {
      background: red;
    }
  }
}

Which outputs:

.foo {
  color: blue;
}
p.foo {
  background: yellow;
}
span.foo {
  background: red;
}
2
  • A comment explaining the downvote would be appreciated... this outputs the desired results, as demonstrated here. Apr 16, 2015 at 18:43
  • 1
    I didn't downvote, seems to produce the results I am after.
    – justinw
    Apr 16, 2015 at 18:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.