How to use parent selector and with class

July 01, 2018

The problem

You have child div (.child) which can be in both "parents" (.parent-a and .parent-b). You want to define a rule to each case. Well, this is not a problem - & selector, right?

Let's remember:

Things are getting be interesting when you want to create a rule for parent (.parent-a) which have another class (.-make-child-orange) and will affect the child (.child).

The structure looks like this:

The closest selector I could think of is .-make-child-orange & but the problem is that it's become to a grandfather selector: .-make-child-orange .parent-a .child

The solution

@at-root and #{} (Interpolation) to the rescue you!

The @at-root directive causes one or more rules to be emitted at the root of the document, rather than being nested beneath their parent selectors. It can either be used with a single inline selector

docs

You can also use SassScript variables in selectors and property names using #{} interpolation syntax

docs

So, combine those options togather and we will use the magic selector: @at-root .-make-child-orange#{&} so the #{&} will be replaced by the selector which aggregated so far:

© 2022 - Moshe Feuchtwander