This Tech Bite was brought to you by Benjamin Jurić, Software Engineer at Atlantbh.

Tech Bites are tips, tricks, snippets or explanations about various programming technologies and paradigms, which can help engineers with their everyday job.

Structuring CSS properly

Stylesheets in a front end project can quickly get out of hand as the codebase grows, and that is when we start to see a lot of !importantlittered around in a “shouting match” to see whose styles get to be applied. Thankfully, over the years, many frameworks or methodologies were developed to curb this issue. Here is a brief explanation of BEM, a methodology which consistently ranks the highest among developers in terms of satisfaction. The entire philosophy of BEM is contained within its name, which stands for Block Element Modifier.

What is a Block?

A block is an element that has some meaning on its own. These would be your input fields, headers, menus, cards etc. It is recommended that they be prefixed with b-, for example: b-menu, b-inputetc.

What is an Element?

You can think of an element as some generic part that has to be attached to a block to convey its meaning, such as titles, labels, or the most generic one of all: item. Common convention in BEM specifies that the elements should be separated with two underscores from their blocks in the name of a class, like so: menu__item, button__label, list__headeretc.

What is a Modifier?

A specialized version of a block or element that allows us to keep the stylesheets DRY and to convey meaningful information in the class name. Some examples of commonly used modifiers are: highlighted, disabled, large, blue etc. Again, common convention suggests that we use two dashes as a separator for modifiers, such as:  button--primary , input--disabledetc.

Let’s see BEM in action:

<style>
  .menu {}	
  .menu__item {}
  .menu__item--selected{}
</style>

<ul class="menu">
  <li class="menu__item"></li>
  <li class="menu__item menu__item--selected"></li>
</ul>

Using BEM or any other methodology helps keep our stylesheets modular, reusable and above all else, gives them structure which helps with scaling.

Leave a Reply