Naming classes in CSS has always been difficult for me😥. Luckily a few months ago I came across the BEM naming convention. A naming convention is an agreed style for naming things(in this case CSS). There are different CSS naming conventions available, such as SMACSS, AMCSS, BEM, etc. For this article, however, I would be talking about BEM.
Prerequisites
- Basic knowledge of Html and CSS.
What is BEM
BEM is short for Block Element Modifiers and is a CSS naming convention for classes in HTML and CSS.
The Block refers to a component such as a header, footer, nav, button, inputs, and the likes.
Element - they are found inside the block(components). they may be seen as children of the overall parent component.
Modifiers on the other hand are used to style a block or an element without affecting other unrelated components
Why use BEM
- BEM helps us write CSS that is easy to read and maintain.
- In large projects, BEM ensures that there are no conflicting styles.
- It conveys the function and purpose of a CSS code.
- It helps developers better understand the relationship between the HTML and CSS in a given project.
How to use BEM
Now that we know what BEM is and why we should use it, its time to dive into the how. The parent components are named by using a single hyphen as seen in the example below
<section class="about-us">
Element class names on the other hand are derived by adding two underscores (__), followed by the element name, like so
<h3 class="about-us__title">best title </h3>
<p class="about-us__text">I love bunnies</p>
when naming modifiers, we use two hyphens (--) followed by the name of the element
<span class="about-us__title--green">ever</span>
Putting it all together we have:
<section class="about-us">
<h3 class="about-us__title">best title
<span class="about-us__title--green">ever</span>
</h3>
<p class="about-us__text">I love bunnies</p>
</div>
we could style it like this
.about-us{
margin: 0 auto;
color: #fff;
}
.about-us__title {
font-weight: bold;
}
.about-us__title--green {
color: #05b993;
}
.about-us__text {
font-size: 24px;
}
Scss makes it even easier for us to style BEM. Styling this with SCSS would look like this
.about-us{
margin: 0 auto;
color: #fff;
&__title {
font-weight: bold;
&--green {
color: #05b993;
}
}
&__text {
font-size: 24px;
}
}
Pretty cool right?
Conclusion
Truly, BEM gives our CSS a solid structure that is easier to understand. You may not get it right now, but I'm sure with time you will. Have fun naming with BEM.
Top comments (0)