Target a parent CSS class with Stylus

Something I don’t like is a pre-concept about some technology before I try it. I’ve been trying Stylus for a couple of months, and I have to say I liked it a lot. One type of CSS architecture I really like is BEM, and these days, I faced a simple problem that probably most of you were able to solve, but as it was new for me, I decided to post here.

The scenario with BEM

Imagine there is a superclass .fabeni. It has a child element and a modificator class (if you want to know more about BEM, I wrote some stuff some time ago ). Something like that:

.fabeni {
background-color: blue;
}
.fabeni__child-element {
border: solid 1px blue;
}
.fabeni--inverse {
background-color: green;
}

Here’s the thing: let’s say we want to target the child element of the modificator class, something like:

.fabeni--inverse .fabeni__child-element {
border-color: green;
}

Using Stylus, I realized three different ways we could write it (probably there is more).

Rewriting the parent class

I have to confess that I’ve already done that. It’s ok! It’s not so beautiful, but it works.

.fabeni
background blue
&__child-element
border solid 1px blue
&--inverse
background-color green
.fabeni__child-element
border-color green

Holding the main class in a variable

Using this preprocessor feature, we could easily reuse the class.

myClass = 'fabeni'
.{myClass}
background blue
&__child-element
border solid 1px blue
&--inverse
background-color green
.{myClass}__child-element
border-color green

Targeting the parent class dynamically

And boom! It’s possible to target the parent class using magic. ^[0].

.fabeni
background blue
&__child-element
border solid 1px blue
&--inverse
background-color green
& ^[0]__child-element
border-color green

I don’t know exactly which Stylus version supports it, but it’s good homework (I tested directly on the Stylus website).

More posts