Photo by @stereophototyp on Unsplash.

BEM — clean and scalable SCSS

In this post, I want to give you a first, short and clear overview of what BEM is, and how to use it.

BEM stands for:

  • Block
  • Element
  • Modifier
marked blocks and elements

An indipendent part of your application.

.header {}
.list {}

An Element is very thight coupled to an outer element and has no stand alone meaning. Elements are delimited with two (2) underscores (__).

// block__element, seperated by double underquotes
.header {
&__logo {}
&__actions {}
}
.list {
&__item {}
}

If your block or element changes its appearance, state, or behavior.

For example, the styling of input in an error state or the state of an item after some action.

Modifiers are delimited by two (2) hyphens (--).

.list {
&__item {
&--visited {}
}
}

Words in classes are separated by a hyphen (-).

.main-content {}

A clean, clear and standardized naming convention is very useful during development.

Think good about the naming of your classes:

  • don’t shorten the names to something unreadable, always use unshortened and clear words for your blocks, elements and modifiers
  • always ask yourself, if a third person reads the classes, would it be clear on the first look what this class refers to
  • keep in mind you are an author, you write your styles once and read them often

If you are new to CSS styling these examples could give you an orientation for your namings.

Use names that are clear about the state of the block or element.

.search {
&--color1 {}
&--color2 {}
}
.search {
&--active {}
&--error {}
}

Use clear names to which blocks and elements your classes refer to

.outer {
border: 1px solid red;
&__inner {
margin: 0 auto;
border: 1px solid black;
}
}
.article {
border: 1px solid red;
&__date-published {
margin: 0 auto;
border: 1px solid black;
}
}

Fast written, but hard to read

.sec-head {}.section-header {}

You should not mix languages, if the project language for the code/styles is English but you are not a native speaker, search for the word in a dictionary instead of writing it in your native language

// german
.zahl {}
.number {}

You should not copy and paste styles that you need in several places, put them into a generic file and import that file where you need the styles.

In the below example the headline is spread over several files, but always the same. You may have a hard time to change it if needed and maybe overlook a place.

// table.css
.headline {
padding: 20px;
}
// card.css
.headline {
padding: 20px;
}
...

Generic wording helps others read your styles

.go-back {}.previous-page-button {}

I hope you liked this short introduction, if you want to read further you may want to visit CSS guidelines or BEM naming for more details.

Loving web development and learning something new. Always curious about new tools and ideas.