When it comes to writing maintainable and scalable CSS code for your web projects, having a clear and consistent naming convention is crucial. One popular methodology that has gained widespread adoption in the front-end development community is BEM, which stands for Block, Element, Modifier. In this blog post, let's dive deep into CSS BEM architecture, explore its core principles with some code samples.
BEM is a naming convention and methodology for writing HTML and CSS code that promotes modularity and reusability. It was introduced to address the challenges of managing complex CSS in large-scale web projects. The main idea behind BEM is to break down your UI into smaller, self-contained components called blocks, and then further modularize those blocks into elements and modifiers. Let's understand them one by one -
button
, span
, text-container
etc.text-container__heading
, text-container__subheading
.button--primary
or text-container__heading--large
or text-container__heading--small
.Here's a practical example of how to implement BEM in your HTML and CSS code.
<!-- HTML CODE -->
<nav class="menu">
<ul class="menu__list">
<li class="menu__item">
<a class="menu__link" href="#">Home</a>
</li>
<li class="menu__item menu__item--active">
<a class="menu__link" href="#">About</a>
</li>
<li class="menu__item">
<a class="menu__link" href="#">Services</a>
</li>
</ul>
</nav>
/* CSS CODE */
.menu {
background-color: #333;
color: #fff;
}
.menu__list {
list-style-type: none;
padding: 0;
}
.menu__item {
margin: 0;
padding: 10px;
}
.menu__link {
color: #fff;
text-decoration: none;
}
.menu__item--active {
background-color: #007bff;
}
Element with class menu
is the block, elements with class menu__list
, menu__item
and menu__link
are the elements of block menu
and .menu__item--active
is a modifier class.
It might look like extra efforts but here are some really significant benefits you should consider -
This becomes even fun and simpler when we are working with a CSS pre-processor like SASS. So, in conclusion, understanding and applying BEM principles will undoubtedly enhance your CSS development skills and make you a more effective front-end developer.
Happy Coding! 🤘