• CSS
  • BEM

CSS - Using BEM

BEM is more of a Methodologies than a Framework, you follow a small set of rules to help structure your CSS in a way that makes it easy to maintain. By following the rules that will be outlined in this article you will be able to better maintain a large CSS codebase.

> BEM — Block Element Modifier is a methodology that helps you to create reusable components and code sharing in front-end development

Rules of BEM

As I find in most things in Web Development or Computer Science in general is naming things can be very difficult. And CSS is no different, by using BEM you are following a set of rules to help structure your rules for ease of use. BEM breaks up these rules into the three distinct area of Block, Element and Modifier, per the BEM.

Block

I think of the Block area as the root of the element on the page. This can be though of as a section all its own, grouping the area as a place that can be lifted and shifted to any place and still hold its meaning.

Naming

Block names may consist of Latin letters, digits, and dashes. To form a CSS class, add a short prefix for namespacing: .block

HTML

<div class="block">Hello</div>

CSS

.block {
    color: green;
}

Element

These are sections inside a block, they can be though of adding meaning to the block, and having none when not in the context of the block it should be part of.

Naming

Element names may consist of Latin letters, digits, dashes and underscores. CSS class is formed as block name plus two underscores plus element name: .block__elem

HTML

<div class="block">
    <span class="block__elem"></span>
</div>

CSS

.block__elem {
    color: red;
}

Modifier

A modifier, like the element, should be part of a block, but can also be on elements. Using theme to change the appearance, behavior or state of the block or element is the main way the modifier is used.

Naming

Modifier names may consist of Latin letters, digits, dashes and underscores. CSS class is formed as block’s or element’s name plus two dashes: .block--mod or .block__elem--mod and .block--color-black with .block--color-red. Spaces in complicated modifiers are replaced by dash.

HTML

<div class="block block--mod"></div>
<div class="block block--size-big block--shadow-yes"></div>

CSS

/* Use modifier class name as selector: */
.block--hidden {
    display: none;
}

/* To alter elements based on a block-level modifier: */
.block--mod .block__elem { 
    text-transform: uppercase;
}

/* Element modifier: */
.block__elem--mod {
    text-decoration: line-through;
 }

Closing

As this article went over BEM is used to help wit the maintainability of large CSS project by following the three stated naming conventions.

References

- Get BEM Website

Cody's logo image, it is an abstract of a black hole with a white Event Horizon.

Cody Merritt Anhorn

A Engineer with a passion for Platform Architecture and Tool Development.