Naming class
Introduction
Most of developers may well feel difficult with making class name, especially when they are styling.
I was using SASS for styling. I occasionally mixed up with inline style using style
(opens in a new tab) property, selector of className
or id
, or just tag selector for styling.
I frequently used className
and id
whenever I used <div>
tag for container (or wrapper) to wrap up elements as below.
Background
But then I was tackled by another front-end developer with the point of using unorganized class names.
Front-end developer: Do you have any conventions of making class name?
Me: No.
Front-end developer: Then how have you been making class name so far?
Me: Just used arbitrary class name if I felt necessary.
Front-end developer: ...(๐)
He seemed to be unsatisfied...
Problem
Then what are some problems if we arbitrarily make class names without any conventions?
- Maintaining will be difficult due to irregularity of class names.
- There could be styling errors deriving from duplicated class names.
Solution
Then what are some solutions for this?
1. BEM Method
BEM method (opens in a new tab)1 indicates method of making class name based on Block, Element and Modifier.
Block
Block is a reusable component that carries out its feature independently.
HTML tags that are usually used for semantic tagging such as <header>
, <nav>
, <section>
, <aside>
are good examples.
For menu wrappers consisting of multiple menu links, for instance, we could make class name mathcing up with its purpose as below:
Element
Element is a unit consisting of block. Element can only have one parent block and cannot be used outside box of block independently. For example, let's say there are three elements: logo wrapper which redirects users to go to home page, menu links wrapper, and menus for authentication.
Whenever you give class name for elements, you use two underscores(__
), followed by element's name.
Modifier
Modifier means modifier word that is used for indicating different state
or style. Modifier should be linked to at least either block or element and can be
represented by two hyphens(--
).
If you take a look at below example, you can make the first menu link's font color which is selected(selected
) as different color.
๐ Implementing BEM method
Below is my actual code of <Footer />
component.
Revising with BEM method will look as below:
2. Module
Module literally means making styling file as module so that we can use it as a JavaScript file by import
ing it.
The best thing about this is that if you inspect those elements on browser, you can see it gives the random id value at the end of class name. Therefore, you don't need to consider block, elment and modifier by yourself as you did in BEM method. However, you must designate class names for every single blocks and elements.