Your busy. You’ve got stuff to do. Here’s BEM in 5 minutes.
BEM is an acronym for Block Element Modifier and it is a naming convention for organising your CSS. Without it, or something like it, CSS can become an unstructured mess that is hard to maintain.
It has a number of advantages:
Scope in this case, means that we can make our CSS more modular by using unique class names, and helps to avoid CSS inheritance. Specificity on the other hand is the idea that sometimes CSS rules will clash - e.g. 2 classes want to be applied to the same HTML element - and therefore a scoring system comes into play. Who wins? Most developers are forced to use
!important to guarantee a winner.
Some disadvantages of using this technique has been aired.
- Some think it will bloat the size of the CSS files (countered by using minification and compression)
- It could make your HTML look ugly (a personal thing and besides, no-one sees the HTML usually anyway).
The three components of BEM - Block, Element and Modifier can be
thought of as follows:
- Block - any HTML element that can accept a class to modify it. E.g. DIV, P or INPUT
- Element - an aspect of that block, which relates directly to one specific block. E.g. price in an input field, or the search part of an input box
- Modifier - something which alters the state of the element. E.g. adding a red box around the search box, or changing the font of a price.
The naming convention can be illustrated with this example:
// Blocks are named as standard CSS classes
If we take a specific example, let’s show a rule for an imaginary input box, which accepts a currency.
Here, our block would be named
order-total and would be applied (most probably) to an INPUT element in HTML.
price is the part of our BEM element that is tied to the block, and has no meaning on its own, making it our element. Lastly,
error is our modifier, and alters how that element is presented.
If you would like to learn more about BEM, see their website.
Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com