Not long ago I wrote about the way I organized my css (it was SMACSS way), but after reading that article many of readers ask me about BEM way, cause I mentioned it several times in SMACSS article, so I decided that would be better to write separate articles about BEM and about comparison of BEM with SMACSS.
That’s why you are here:)
Firstly, lets talk about reasons to use BEM in css. And here will be the same reasons what we read about SMACSS. To make our styles readable, quick editable, scalable and for better work with co-workers we need to organize our styles.
But you will ask “Why BEM? What is the difference?”.
The main idea of BEM – is separating our layout into Blocks, Elements, Modifications.
So, let’s describe each of those and you will see and feel the difference.
Blocks
Blocks are some independent parts of layouts and they can be used more than once at our page. Also, Block can’t somehow influence outside area(margins, borders, etc.) – that helps to use Blocks few times. As well, Blocks can be used inside other Blocks. So, Blocks in BEM are something like Modules in SMACSS.
Elements
Hmm, if Block(BEM) == Module(SMACSS), what the fish is the Element?
Elements are parts of Blocks that can’t be used outside Block. And it’s ok to nest elements inside elements.
But, I forget about some BEM’s feature, I’m talking about syntax.
For example, code of element:
.blockName__elementName {
something: cool;
}
Hope you see “__”. It is necessary when your write css rule for your Element. And that’s cool cause if look into html, you’ll understand that element is depended just this Block.
Also, let’s look at nested elements:
<div class=”block”>
<div class=”element1”>
<div class=”element2”></div>
</div>
</div>
——————————————-
.block {}
.block__element1{}
.block__element2{}
That’s because elements just depend on blocks.
PS: I don’t find anything similar in SMACSS.
Modifiers
That’s something that change behaviour, appearance or state of our Element or Block. That’s something like what we write in state.css, if its SMACSS way and it can describe color, size, opacity etc.
However, syntax!
.btn{
width: 200px;
}
.btn–red {
color: red;
}
That’s what I mean. “–” in BEM it’s for modifiers. And it’s also cool if you open just html and can understand all what is happening with object.
Now let’s talk a bit about file structure of BEM.
In our src folder or assets folder, or styles folder or … we just create files that contain just styles for separate Blocks. Yes, and that’s all.
Because of Elements and Modifiers depend on our Blocks, it’s better to write it near Blocks or inside(if you use Less/Sass).
————————————————————————————
LifeHack for fellas who using less/sass:
.blockName {
&__elementName {}
&__elementName{
&–modifier{}
}
&–modifier{}
}
Hope you’re cool and understand what I mean. If no, you’re young and well motivated person, and after reading that article will google about less/sass and till next morning will know more than I do 😉