An Introduction to BEM – “DO Less Get More” CSS Approach

28 / Feb / 2017 by Poonam Baveja 0 comments

Front end development and Coding is an art. Efficiency of code increases if it is organized in a right way. Certain questions that you need to address are:

a) How long it takes for you to write code? (Consider efficiency while writing the code)
b) How much code you will have to re-write for similar task? (Make sure the code is reusable)
c) How much time does browser take to read your code? (Optimize the performance)

BEM provides more structured way to organize your CSS code thereby increasing the productivity. BEM stands for Block, Elements and Modifiers. These three approaches or techniques help to maintain a single codebase and reduce complexity.

Block: Block is a standalone entity or piece of html code that is meaningful by its own. eg: header, menu, container, input, checkbox
Element: Element is a part of the block that has no standalone meaning. eg: header title, menu item, list item, checkbox caption
Modifier: Modifier is a flag on the block or element that is used to modify the behaviour or appearance. eg: disabled, checked, fixed, size big, color red.
Syntax:-

       .block {}
      .block__element {}
      .block--modifier {}

If you want to categorize a search bar in BEM, it can be broken down as:-

      .site-search {} /* Block */
      .site-search__field {} /* Element */
      .site-search--full {} /* Modifier */

BEM

Let’s take an example of above buttons. As a usual case, we are using normal buttons here:

      .button {
      background-image: linear-gradient(#EEE, #DDD);
      display: inline-block;
      border-radius: 2px;
      border: 1px solid #D5D5D5;
      padding: 6px 12px;
      font: 600 13px/18px Helvetica, arial;
      }
     .button--success-state {
      background: #569E3D linear-gradient(#79D858, #569E3D) repeat-x;
      color: #FFF;
      border-color: #4A993E;
      }
     .button---danger-state {
      color: #900;
     }

Here’s more information and a Demo Link

Why should you consider using BEM? Outlined below are the few benefits:

1. Modularity: There is no problem of cascading. This helps in using the codebase of one project to another.
2. Reusability: Writing code for independent blocks and using them intelligently reduces the CSS to be written.
3. Organised Structure: Easy and simple to understand with the help of declarative syntax given BEM.

Other benefits include easy debugging, increase in development speed and quick implementation of new features. Hope with so many benefits and multiple applications, you would be able to use BEM successfully for your projects.

FOUND THIS USEFUL? SHARE IT

Leave a comment -