Thoughts About SCSS and BEM

10 May 2013

Writing efficent CSS is hard, we all know that. There are many articles out there regarding this topic. I don't want do repeat everything said in these articels. Rather I want to share my thoughts about BEM in combination with SCSS.

What is BEM?

BEM stands for BlockElementModifier and is a naming convention created by Yandex. I first heard of it in Harry Roberts articel MindBEMding – getting your head ’round BEM syntax, if you haven't heard of it yet you should definitely read that articel first.

Using BEM in SCSS

I am using SCSS to write my CSS but when it comes to BEM the syntax isn't optimal. SCSS is great but can be improved reagarding BEM syntax.

A simple example

This is what a BEM structure would currently look like in SCSS

.block{
}
    .block__element{
    }
    .block--modifier{
    }

To be honest, this is just plain CSS no SCSS feature was used. But what is the Problem with that? There is to much replication. You can see that '.block' is written three times there.

In SCSS there is the Referencing Parent Selectors: & which is most often use in combination with pseudo classes like :hover, :before or :after.

But woudn't it be great to write BEM SCSS like this:

.block{
    &__element{
    }
    &--modifier{
    }
}

to get:

.block{
}
.block__element{
}
.block--modifier{
}

The great thing about this would be that elements and modifiert would be block agnostic. So it would be possible to have shared modifiers like this:

%sharedModifier{
    &--blue{
        color:blue;
    }
    &--green{
        color:green;
    }
}

.block1{
    @extend %sharedModifier;
}

.block2{
    @extend %sharedModifier;
}

Resulting in:

.block1{
}
.block2{
}
.block1--blue, .block2--blue{
    color:blue;
}
.block1--green, .block2--green{
    color:green;
}

Wrapping up

It's just a small change to SASS but, in my eyes, it would greatly improve the readability of SCSS.

I would like to know what you think about this syntax. Is it superfluous, or do you think it's usefull? Have you any other idea on how to improve SCSS?