Introduction to CSS BEM Naming Convention
Table of Contents
BEM (Block, Element, Modifier) is a naming convention for class names in HTML and CSS. It makes HTML and CSS code more orgranized.
Concepts and Usage #
Don’t worry if you don’t understand it at first. There are examples later on.
- Block: independent HTML element (such as
<nav>
), and it may not contain any HTML elements. - Element: any HTML element inside a block, it can’t be independently used (example:
<li>
), and double underscores__
should be added before it. - Modifier: it indicates the state or appearance of a block or element, and double hyphens
--
should be added before it. - Use single hyphen to connect words, example:
search-form
. - An element only belongs to a block, not another element. Wrong:
block__element1__element2
. Correct:block__element2
. - When using modifier, keep the class name without the modifier. Example:
<a class="menu__link menu__link--active" href="/en/">Home</a>
.
HTML Demo #
<nav>
is a block, which contains the elements <ul>
, <li>
and <a>
. --active
is a modifier.
|
|
CSS Demo #
|
|
SCSS Demo #
I strongly recommend SCSS because you can use the parent selector &
to group together all styles of both a block and its elements. This structure clearly reflects the hierarchical relationship between them.
|
|
Alternative: Atomic CSS #
If you find BEM too verbose or difficult to maintain, you can try atomic CSS frameworks like Tailwind CSS and UnoCSS that provide utilities (predefined classes). Developers only need to write predefined class names and don’t need to write CSS code. Here are some utilities in Tailwind CSS:
|
|
To rewrite the previous CSS code in Tailwind CSS (online demo):
|
|
Further Reading #
- https://en.bem.info/ (official guide)
- https://getbem.com (unofficial guide)
- Naming convention / Methodology / BEM
- troxler/awesome-css-frameworks: List of awesome CSS frameworks