Always Twisted

{ Slightly Bizarre Ramblings Of A Front-End Developer }

Even Easier BEM-ing with Sass 3.3

Back in October last year (2013) Una wrote a blog post about using Sass 3.3s new @at-root directive to create some sexy easy BEM nesting possibilities.

BEM (Block, Element, Modifier) from Yandex allows developers to create a simple naming convention helping make your CSS more modular and portable.

.block{} // the ‘thing’ like .list
.block__element{} // a child of the block like .list__item 
.block--modifier{} // a variation of the ‘thing’ like .list-—vertical

Using the way Una described you would write some Sass like this ...

.block {
    @at-root #{&}__element {
    }
    @at-root #{&}--modifier {
    }
}

... which would print out like this ...

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

When Sass 3.3.0rc3 came out a couple of weeks ago they changed this. For the better. Natalie explains the goings on in this gist (via Jed Fosters roughdraft.io).

Now instead of needing ugliness of @at-root #{&} which in honesty was putting me off, you can now just use the ampersand. This makes your Sass look so much nicer (not that that matters) and quicker to write, obviously.

So now you would write some Sass like this ...

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

... which now prints out like this ...

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

I’m sure you can see how even sassier your Sass looks and the results remain the same.

For a ‘real world’ case of showing this technique and using BEM let’s have a look at some main navigation HTML

<nav role="navigation" aria-label="primary">
  <ul class="nav__list">
    <li class="nav__list__item">
      <a href="" class="nav__link"></a>
    </li>
    <li class="nav__list__item">
      <a href="" class="nav__link--active"></a>
    </li>
    <li class="nav__list__item">
      <a href="" class="nav__link"></a>
    </li>
  </ul>
</nav>

we could then write some Sass like this (being all BEM’y I’ve not added a class to the main nav (through personal choice)) ...

nav[role=navigation] {
} .nav { &__list { &__item { } } &__link { &--active { } } }

You’d get this result.

nav[role=navigation] {
}
.nav {
}
.nav__list {
}
.nav__list__item {
}
.nav__link {
}
.nav__link--active {
}

That’s pretty sweet if you ask me, makes Sass nesting work nicely without giving too much to the inception rule to worry about. I’ve also gone on to make a version of Harry Roberts’ Beautons using it too.

What examples can you think of that this would be great for?


So you obviously love Sass. So how about signing up to a weekly newsletter of all things Sass direct to your inbox, curated by me?

Categories

CSS HTML Sass Did you like this post? Hire me.
blog comments powered by Disqus