DEV Community

Anand Doddamani for Catalysts ReachOut

Posted on

How To Name Classes in HTML and CSS using BEM

Hello Buddies,

In Today's story we are discussing about naming convention in HTML and CSS. 

We are Discussing about BEM naming convention where B - Body, E - Element, M - Modifier. You may had a glance of naming classes similar as mentioned below

//Wrong
.catlystNavbar{ ... }
.catlystNavbarLogo{ ... }
.catlystNavbarBg{ ... }

//Correct
.catalyst-navbar {  ...}
.catalyst-navbar__logo{  ...}
.catalyst-navbar--bg{  ...}
Enter fullscreen mode Exit fullscreen mode

BEM attempts to divide the overall user interface into small reusable components.

To understand efficiently let us take an example of our a navbar
Catalysts Navbar

Image description

The above navbar represents as element, such as a block of design.

Which represents the first letter of BEM that is Block and the component styled similarly as shown below

.catalyst-navbar{  ... }
Enter fullscreen mode Exit fullscreen mode

E - Element

E stands for Element in BEM

For instance, the catalyst-navbar a logo and links

The logo and links are all elements within the component. They may be seen as child components, i.e. children of the overall parent component.

Using the BEM naming convention, element class names are derived by adding two underscores, followed by the element name.

.catalyst-navbar__logo{  ... }
.catalyst-navbar__content{  ... }
Enter fullscreen mode Exit fullscreen mode

M - Modifier

M stands for Modifier in BEM

What if the navbar was modified and we could have a blue or a red background

In the real world, this could be a red button or blue button. These are modifications of the component in question.

Using BEM, modifier class names are derived by adding two hyphens followed by the element name.

For Example:

.catalyst-navbar--bg{  ... }
.catalyst-navbar--red{  ... }
.catalyst-navbar--blue{  ... }
Enter fullscreen mode Exit fullscreen mode

Here is the final code I wrote for this navbar

Image description

Now the question arrise , Why naming convention is required ?

Naming things is hard. We're trying to make things easier, and save ourselves time in the future with more maintainable code.

Naming things correctly in CSS will make your code easier to read and maintain.

If you choose to use the BEM naming convention, it will become easier to see the relationship between your design components/blocks just by looking at the markup.

Top comments (1)

Collapse
 
naucode profile image
Al - Naucode

Thanks, it was a good read, bookmarked, and followed!