I want to generate this kind of CSS, where a style is applied to an element and several of its descendants, using SCSS
.a,
.a .b,
.a .b .c,
.a .b .c .d { /* Styles */ }
In this related question How to apply a style to both parent and child in SCSS I learned that I could achieve something similiar using &. I've tried this:
.a {
&, .b {
&, .c {
&, .d {
color: blue;
}
}
}
}
which resulted in the following css:
.a,
.a .d, /* Not wanted */
.a .c, /* Not wanted */
.a .c .d, /* Not wanted */
.a .b,
.a .b .d, /* Not wanted */
.a .b .c,
.a .b .c .d {
color: blue;
}
I understand that this happens, because & will include the whole previous selection, which always includes .a (or .a .b on the next stage).
However, I'm not sure how to fix this.
Is it possible to get the result I want using SCSS?
Please note that I'm mainly asking out of curiosity and that I'm not very familiar with some aspects of SCSS. Mabye functions, interpolation or mixins could be used?
Retrictions
- Selectors could be much longer and much more complex then in the example above. I would like to repeat them only as often as necessary.
- There could be many more styles I want to apply, not just one.
Discarded solutions
Some obvious, but rather bad solutions I could think of
hard-coding it exactly as I would do in plain CSS. Well the point of question is how to avoid exactly this ;)
repeating the style on each level. Even with variables this would be more repetition then hard-coding it. I mean something like this:
.a { color: blue; .b { color: blue; .c { ...using
color: inherit. In this case I would still need to repeat the inherit.