Sep 30, 2014 | sass

Nesting Sass @imports, with BEM

!
Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

Yesterday Trey Piepmeier wrote a quick blog post showing that you could import a Sass import within a selector.

// main.scss
.context {
    @import 'embed';
    font-size: 42px;
}
// _embed.scss
.child {
    color: red;
}

Produces:

.context {
    font-size: 42px;
}
    .context .child {
        color: red;
    }

This is a really clever trick; I've only ever used @import to pull in things to the top level of the document. Unfortunately, I can't use it, for two reasons:

First, we don't like to use descendant selectors. Like I've written before, we use BEM instead of descendant selectors in our CSS.

Second, we've actually tried, and failed, to use style namespaces. For the most significant example, we tried namespacing the primary content section of our pages under .content. It seemed really clever, because we could then isolate the styles we were applying there to just apply in that context.

The problem was, every selector within that namespace instantly had an increased specificity. It was no longer h1--it was now .content h1, which means you could no longer style that h1 later by adding a single class like .news-title, because .news-title isn't as specific as .content h1. So, you'd have to write .news-title, .content .news-title just to make it work. It became a huge mess.

BEM and nesting Sass imports

Along comes BEM, to save the day. So, I thought, why can't we use Trey's trick for BEM? Turns out we can.

// main.scss
.context {
    @import 'embed';
    font-size: 42px;
}
// _embed.scss
&__child {
    color: red;
}

Produces:

.context {
    font-size: 42px;
}
    .context__child {
        color: red;
    }

The end

Granted, I'm not sure if this is even useful--why would you want to separate out the children elements and modifiers of a BEM module from their parent block? But maybe there are contexts where you'd want to. So, now you know: You can do it.


Comments? I'm @stauffermatt on Twitter


Tags: sass

Subscribe

For quick links to fresh content, and for more thoughts that don't make it to the blog.