Using parent selector prefixes in SASS

Slava Fomin II
A Path of Developer
2 min readMar 26, 2019
Parents with their child selector

Today, I was working on a button component in React for our design system at DomClick.

We’ve decided, that a single universal component should handle both cases when the button behaves as a link and as a button, therefore, it should use either <a> or <button> native DOM elements under the hood.

So, in order to style it, we would need a CSS code like the following:

I’m using SASS for all our CSS needs, so I’ve decided to find a way to implement it using SASS in a most concise way in order to avoid specifying class name multiple times in our code (using DRY principle).

Intuitive, but incorrect

The most intuitive thing to do (without looking into documentation) was to write the following easy to understand construction:

But, sadly, it didn’t work. SASS language doesn’t allow ampersand directly after the prefix selector. If you would add space between the prefix selector and the ampersand it would work, but it will produce different result. Not what we are expecting.

Harder, but working solution

Digging a little deeper, I found a way to implement the desired functionality by using more advanced (but harder to read) features of the language, namely: @at-root and interpolation:

The @at-rootwill move the code block out of the parent selector and the #{&}will insert the parent selector after the specified prefix.

I hope this will help you to write more concise code, but if you think that SASS should provide a better syntax for this usage scenario, make sure to support the proposal.

Cheers!

--

--