Frank N
Frank N

Reputation: 10396

Sass Ampersand to add Tag to Class

I have some Sass like this:

.zbounce1, .zbounce2, .zbounce3, .zbounce4
    animation-name: bounceIn
    animation-duration: .5s
    animation-timing-function: ease-in-out

span.zbounce1, span.zbounce2, span.zbounce3, span.zbounce4
    display: inline-block

I would like to simplyfy the second part to a nested bit of the first part, so I don't have to mention every class again:

    span.&
        display: inline-block

Sadly, this is not legal. (The other way round, specializing a bunch of styles with a nested &.anotherClass is easy...

Any workaround to achieve this? (perhaps with the @extendOnly-Placeholder?) or some funky sass concatenation...?

Upvotes: 5

Views: 1178

Answers (2)

Frank N
Frank N

Reputation: 10396

Ladies and gentlemen...

.zbounce, .zbounce1, .zbounce2, .zbounce3, .zbounce4, .zbounce5
    ...
    @at-root #{selector-append(span, &)}
        display: inline-block

getting me, what I want:

span.zbounce, span.zbounce1, span.zbounce2, 
span.zbounce3, span.zbounce4, span.zbounce5 { 
    display: inline-block;
}

Thanks to @ovokuro for pointing me into therightdirection!

Upvotes: 1

delinear
delinear

Reputation: 2795

You can achieve this in native sass, it's just a bit convoluted. You need to use selector-append to add the span to all of the selectors, and @at-root to do so at root level (if that makes sense? it's hard to even explain). Basically it looks like this:

.zbounce1, .zbounce2, .zbounce3, .zbounce4 {
  animation-name: bounceIn;
  animation-duration: .5s;
  animation-timing-function: ease-in-out;
  @at-root #{selector-append(span, &)} {
    display: inline-block;
  }
}

Which should output this result:

.zbounce1, .zbounce2, .zbounce3, .zbounce4 {
  animation-name: bounceIn;
  animation-duration: .5s;
  animation-timing-function: ease-in-out;
}
span.zbounce1, span.zbounce2, span.zbounce3, span.zbounce4 {
  display: inline-block;
}

Here's a Codepen example (you'll have to view source and look for the style block in the header to see the output, I'm not sure how else to demonstrate it but hopefully this helps!)

Upvotes: 4

Related Questions