It’s important for CSS to be modular. Without modularity, selectors are fragile and it’s hard to be confident that changing one style won’t inadvertently break a different style somewhere else.
How does BEM help?
BEM solves modularity by encapsulating styles within a “Block”. Here’s an example from BEM.info.
__ separates the Block (
search-form) from the Element (
BEM also has Modifiers, indicated by a
Note: getBEM.com uses
-- instead to denote Modifiers.
BEM meets Bootstrap
What if you’re working on a site where the CSS is based on Bootstrap? Is there a way to do BEM that fits with Bootstrap’s naming conventions?
In fact, Bootstrap is modular in a similar way to BEM.
Bootstrap’s conventions say, “Prefix classes based on the closest parent or base class”.
For example, Bootstrap Dropdowns look like this.
<div class="dropdown"> <div class="dropdown-menu dropdown-menu-right"> ... </div> </div>
- dropdown is a block
- menu is an element
- right is a modifier
But what about…
Modifiers on Blocks
What would happen if you wanted a modifier on the block? For example, dropdown-disabled ?
How would you know if disabled was a modifier or an element?
- An Element is, “A composite part of a block that can’t be used separately from it”
- Modifier “defines the appearance, state, or behaviour”
Blocks and Elements are “things” and so should be nouns. (Remember: nouns make good class names).
Modifier describe qualities of a thing, so should be adjectives, like disabled, active, large, expanded and primary.
Words like is, has and with also indicate modifiers e.g. nav-as-tabs and nav-with-fill.
Elements with multiple words
What about a class like search-form-content: is the Block “search” or search-form ? How can you tell without using underscores?
Usually it’s clear from the context. Here’s a modified example from BEM.info.
<form class="search-form"> <div class="search-form-content">...</div> </form>
You can see that search-form is the block and “content” is an element. (“content” is a noun so it isn’t a modifier).
If you face a situation which needs clarification then you can always add a comment to explicitly say what the block is.
You can have BEM’s modularity and Bootstrap-friendly naming.
I believe that many developers already do something similar to what is outlined in this post.
If you’re interested in other words of making your CSS modular then check out SMACSS module rules.