BEM

During my experience as web developer, I have met some problems with the maintenance of CSS. For small project this could not be a very big problem but when a project survives for long time is necessary a way to manage them.

In fact, I believe that if the web developer does not use a way to manage the stylesheets these can only grow in the time and a change in a class or in an html element can change the style in an unexpected way and to minimize this risk the web developer will change the CSS only adding styles.

Today, I want to talk about a methodology to manage CSS stylesheet, this is BEM.

BEM is acronym of Block Element Modifier and is a methodology very similar to OOP, in fact while in OOP there are classes, properties and methods in BEM there are blocks, elements and modifiers.

 

What is a Block?

A block is an independent entity and can contain other blocks or elements.
(in a base HTML page examples of blocks could be the header, content and footer)

What is an Element?

An element is a part of a block that performs a function.
(in a base HTML page examples of elements should be an header’s content)

What is a Modifier?

A modifier is a property of a block or an element which is different for look or behavior.
(in a base HTML page with two images having same properties (size,border, etc.) except to the background where the first one is yellow and the other is red. In this example the two images have two different modifiers on the background property)

In the following picture the header, content and footer are blocks, the search box is an header’s element, instead the images are content’ elements with different modifiers (size and background color).

Diapositiva2
After describing what is BEM, this is the syntax to adopt in html and css for each element in a page:

<block>__<element>–<modifier>

In the give example for the header we have (using SASS syntax):

.header {
     &__searchbox {
     }
}

.content {
     &.__image {
     }

     &.__image–first {
     }

     &.__image–second {
     }

     &.__image–third {
     }
}

Using BEM gives the following advantages:

  • Each element in a web application has a unique identifier well defined and it is easily understandable the link between CSS and HTML page;
  • The CSS is organized in blocks, each block contains elements and modifiers. If the developer uses also tool to generate CSS automatically such as Sass or Less can improve the code adding variables, mixin, etc;
  • More controls on CSS, the CSS file becomes changeable and maintainable;
  • The dev team has a methodology to write CSS which is understood from everyone.

 

Leave a comment

Create a website or blog at WordPress.com

Up ↑