Today I learned: How to append the parent selector at the end of a Sass rule declaration
Posted on
Heads up
Regarding the below examples... Of course this approach sounds over-engineered, but here, the purpose is educational, and therefore using simple examples to demonstrate the Sass language capability seemed appropriate.
Base design
Let's take the simple below Sass declarations:
.sidebar {
.cta {
background-color: teal;
color: white;
}
}
At this point, all Call To Actions (a.k.a CTA) from the sidebar have a
background of teal
and a text color of white
.
The CSS output for this is:
.sidebar .cta {
background-color: teal;
color: white;
}
"Power users" design
Now let's say that you have "power users" who should, by design, experience an alternative branding for these sidebar CTAs.
In order to customise various elements and components in the page, it has been
decided to position a power-user
CSS class on the highest page element, i.e
the <html>
tag.
To add to that; you want to keep the override of the branding close to its original definition in your Sass file.
This is where you need to append the parent selector, from within a nesting
block, with the .power-user
selector. You can achieve that using Sass'
@at-root
at-rule.
Now let's revisit our example from above and add the custom "power user" branding.
.sidebar {
.cta {
background-color: teal;
color: white;
@at-root .power-user #{&} {
background-color: orangered;
}
}
}
The CSS output for this is:
.sidebar .cta {
background-color: teal;
color: white;
}
.power-user .sidebar .cta {
background-color: orangered;
}
Et voilà! You get the .power-user .sidebar .cta {}
rule you were aiming for.