Search code examples
csscompilationstylus

Create Stylus variable with several classes and concatenate in compilation


I'm in the situation that I want to assign the same CSS rules to several selectors and normally I use Stylus interpolation assigning several classes to a variable.

pages = '.home, .about, .contact'

{pages}
    a
        color black

This yields in:

.home a, .about a, .contact a {
    color: black;
}

But I have an issue that I would like to resolve in an elegant way if it would be possible. Let's say now I want to use the same variable to concatenate with another one, for example:

.general
    &{pages}
        a
            background-color black

This yields in the expected way:

.general.home a, .general .about a, .general .contact a {
    background-color: black;
}

I would like to generate a "double class" selector in each case, not only the first one. For this I have tried to use an iteration method that works, but I'm not satisfied at all:

pages = home about contact

.general
    for class in pages
        &.{class}
            a
                color black

This yields in:

.general.home a { color: black; }
.general.about a { color: black; }
.general.contact a { color: black; }

This is not too bad, but when I want to use the same variable in the first way (this is the most common use that I give to this variables), I can't because it's not compiling with the correct selector syntax.

Can you think of any way to achieve this?

Thanks in advance!


Solution

  • You can add & to every class in the string of selectors:

    pages = '&.home, &.about, &.contact'
    
    .general
      {pages}
        a
          color black
    

    Even automatically with replace bif:

    pages = '.home, .about, .contact'
    
    .general
      {replace('\.', '&.', pages)}
        a
          color black