BEM is a naming convention for CSS classes that facilitates writing clean and organized CSS. This blog post will boil down what BEM is and how to use it in this “In a Nutshell” series entry.
BEM In a Nutshell:
- BEM stands for Block, Element, Modifier, each of which represent the 3 parts of a class name using this convention.
- The format for the BEM naming convention is
<Block>__<Element>--<Modifier>where Block, Element and Modifier represent a part of the class name (see Definitions below).
The reason BEM is a useful naming method is because it explicitly describes which element(s) your CSS rules apply to and encourages incorporating Separation of Concerns in your CSS. This makes maintaining and changing your CSS much easier to do, since making a change for one class named using BEM will not inadvertently and unexpectedly break or change the presentation of other elements.
- Block: A name that describes an HTML element that can be independently moved around in the HTML document and not lose it’s meaning.
- Element: A name that describes an HTML element that is a child or descendant of a Block element and depends on that Block element to retain it’s meaning.
- Modifier: A name that describes an alternate state that an element can get into. For ex., a
BEM IN ACTION:
Let’s say you have a form that is part of a login page on your website. We want to use BEM to construct class names for various elements to apply CSS.
The following is an example using the BEM naming convention to apply class names to the various elements:
<form class="loginForm"> <input type="text" name="username" class="loginForm__username-input" /> <input type="password" name="password" class="loginForm__password-input" /> <button type="submit" class="loginForm__submit-button--disabled">Log in</button> </form>
loginForm is the Block element class name because the form that it labels can be moved anywhere in the document and still retain it’s meaning – it is the form specifically for logging in.
The username and password inputs are not independent of the login form, so they are labeled using the Element name part in the class name. This part is preceded by the Block they depend on (
loginForm) followed by a double underscore, so they are labelled with descriptive class names such as:
The submit button of the form starts out in a disabled state, so we add a Modifier name to the class name we will use to set the CSS for it. The Modifier name describes the state of the element preceded by two dashes, the Element it belongs to and the Block followed by two underscores: