If you are working with SCSS/SASS, you might still wonder how to organize your CSS classes. The pre-SASS conventions like OOCSS seem not to be necessary in SCSS, since SCSS has mixins, placeholders and variables.
But there is one very powerful feature of SCSS, which we want to take advantage of now: inline sub selectors in selectors.
.b-post {
.title {
color: #f00;
&:hover {
color: #fff;
}
}
&.is-new {
background-color: #aaf;
}
}
will transform into:
.b-post .title {
color: #f00;
}
.b-post .title:hover {
color: #fff;
}
.b-post.is-new {
background-color: #aaf;
}
Blocks, elements and modifiers
In nikita.kickstarter we use blocks, elements and modifiers. This naming is not new, since it's also part of yandex's BEM (block, element, modifier)!
There you see a special class b-post
, which we call a block, thus prefix it with b-
(see WHY-NOT.md,
why we decided against a different prefix).
The title
is an element within the block. And now comes the very important part: title
MUST NOT be defined globally. Since
it is not a block, it may only appear within a blocks definition. So please do not use a _global.scss
to define non-block
globals.
The is-new
is a modifier of the block. Modifiers are prefixed with is-
(see WHY-NOT.md, why we decided
against a different prefix).
Refactoring an element into a block
If you stick to those three rules, you will have to refactor an element into a block. This is not a big deal, since at the beginning your new block will only be part of its parents block.
Let's say we want to transform the title
into a block. We end up with this scss:
.b-post {
&.is-new {
background-color: #aaf;
}
}
.b-title {
color: #f00;
&:hover {
color: #fff;
}
}
and everywhere in b-post
, where there was a title
, we have to change it to b-title
. That was straightforward, wasn't
it?
It's a good idea, to create a separate file for each block.
Own files for your blocks
Even though you (may) have source maps, it's usually a difficult to find a scss or css definition, if you have one BIG file. If you use those blocks you can put each in one file.
So b-post
goes into _b-post.scss
. So whenever you encounter a .b-post *
css rule in your firebug or firefox/chrome
dev tools, you know: it is defined in .b-post.scss
.
If you want to have a catch-all (glob like behaviour) in your primary styles.scss
, use sass-globbing and
define it like this:
include('_b-*.scss')
And since blocks only contain block specific content, the inclusion order does not matter! So it is safe to do this!
Another advantage: Your favorite editor, will show _b-post.css
in the Tab, so you can easily open each block on it's own
and keep the overview.
Conclusion
Blocks make your CSS maintenance a breeze, when it comes to finding css definitions or keeping an overview about what you have and when it is safe to remove a block.
The next post of this series, explains how to handle media queries with blocks.