CSS naming conventions are used to create consistent and meaningful names for classes, IDs, and other selectors. These conventions help improve stylesheet readability, make collaboration easier, and reduce errors.
BEM (Block Element Modifier) is one such methodology for naming classes in HTML and CSS.
This is how CSS written in BEM style would look like:
Notice the usage of underscore and hyphen in class names. Each part of the class name has
a specific meaning. But before diving deep into the technicalities of naming the classes, let's
establish a foundation by understanding the three terms in BEM
.
-
Block: This refers to a standalone entity and should be thought of as the parent component.
A block can be a container, menu or anything which is independent and can be reused.
-
Element: Elements are parts of a block with no standalone meaning, they are nested inside their parent block.
While giving the class names, element name is separated from the block name with a double underscore
block_name__element_name
.
An input component or a button nested inside a div
block can be thought of as an element.
-
Modifier: These are flags for blocks or elements and can be used to change their appearance, such as color, size, state, like a button being disabled
, or behavior.
The modifier name is separated from the block or element name with a double hyphen block_name--modifier
or
block_name__element_name--modifier
.
Now, let's look at a simple form
component to see how BEM can be applied.
The codeblock demonstrates the usage of the BEM methodology to create a well-structured search-form component.
Notice the two classes search-form__button
and search-form__button--primary
we have used for the button element. The first class
can be used to style any button within a form in our page, while the second class uses a modifier primary
to give a specific
styling to the button, which is why --
is used to separate the modifier name primary
from it's counterpart.
Why should we consider BEM?
- If we want to make a new style of a component, we can easily see which modifiers and children already exist.
- If we are reading the markup instead of CSS, we should be able to quickly get an idea of which element depends on another.
- Designers and developers can consistently name components for easier communication between team members.