We recently incorporated BEM into all our frontend (HTML, CSS, SCSS) web development and have had mixed feelings about its advantages and disadvantages ever since. We have also been busy researching BEM best practices and its support in CSS pre-processors, such as LESS & SASS.
In this article we take a quick look at what BEM is, why you should care about it, and the pros & cons of using BEM.
BEM stands for Block Element Modifier and is an HTML & CSS naming methodology that helps you create reusable components and aids code sharing in frontend development.
BEM encourages you to take a modular approach to constructing HTML/CSS, such that every HTML component (or "module") you code consists of a block, element(s), and modifier(s). Take a look at http://getBEM.com for a detailed guideline and sample code.
You should care because BEM fixes the two biggest problems with plain old CSS:
Inheritance in CSS is infinite. Unlike other programming languages, there is no function scope or closure. Styles that you define at the top of the file will flow down (cascade) and will never reach a bottom. BEM avoids CSS inheritance and provides some sort of scope by using unique CSS classes per element.
And why is CSS specificity bad? Simply because you need to become more specific to win over existing specificity. And more often than not, developers find themselves using very long nested CSS selectors or the '!important' keyword. Either of those two approaches results in a complicated mess of overlapping and conflicting CSS rules.
BEM reduces style conflicts by keeping CSS specificity to a minimum.
In addition to fixing CSS inheritance and specificity issues, incorporating BEM into your projects also brings in the following benefits:
As with everything, BEM also comes with a few downsides but these can easily be mitigated by implementing a few extra steps while configuring your frontend build process.
From our brief experience with BEM so far, the pros do seem to outweigh the cons. So we would recommend trying BEM for your next project, if you haven't already. And until we dive deeper, it does seem more sensible to BEM than not!