lainas
lainas

Reputation: 21

Using CSS prefix selector with SASS ampersand

In sass we can do some kind of class name concatenation with this:

//Sass
.button{
    &-1{ background-color: red; }
    &-2{ background-color: blue; }
}

//Result
.button-1{ background-color: red; }
.button-2{ background-color: blue; }

Can I somehow do concatenation on top of a prefix selector like this so that I don't have to use a base class or @extend:

*[class^="button-"]{
    width: 20px;
    height: 20px;
    border: 1px solid black;

    &-1{
        background-color: red;
    }
    &-2{
        background-color: blue;
    }
}

I could achieve the same results with defining a base class and then adding specific styles after that like this:

.base-button{
    width: 20px;
    height: 20px;
    border: 1px solid black;
}

.button{
    &-1{ background-color: red; }
    &-2{ background-color: blue; }
}

But I would then have to go and add that base class to all elements. Another approach is using the @extend directive like this:

.button{
    width: 20px;
    height: 20px;
    border: 1px solid black;
}

.button-{
    &1{
        @extend .button;
        background-color: red;
    }
    &2{
        @extend .button;
        background-color-blue;
    }
}

I guess my question is if there is a particular reason why sass doesn't support class concatenation when the parent selector is a class prefix selector. Isn't it safe to make the assumption that the prefix used in the selector can be used for concatenation when that parent selector has nested classes with &? Or am I just doing something wrong with my sass?

Thanks!

Upvotes: 2

Views: 1504

Answers (1)

Andre Figueiredo
Andre Figueiredo

Reputation: 13425

SASS does a objective, literal concatenation when you use &, so:

*[class^="button-"]{
    width: 20px;
    height: 20px;
    border: 1px solid black;

    &-1{
        background-color: red;
    }
    &-2{
        background-color: blue;
    }
}

will generate:

*[class^="button-"]{
    width: 20px;
    height: 20px;
    border: 1px solid black;
}
*[class^="button-"]-1{
    background-color: red;
}
*[class^="button-"]-2{
    background-color: blue;
}

which has invalid syntax, because a selector such as *[class^="button-"]-1 is not valid CSS.

You can create a mixin to get what you want. But frankly, these solutions should be last last resort, like selector by an attribute other than class name or id. Even that, just KISS to keep readability and maintainability.

Upvotes: 1

Related Questions