Cyrus Yip's blog

Introduction to CSS BEM Naming Convention

Cyrus Yip
Table of Contents

BEM (Block, Element, Modifier) is a naming convention for class names in HTML and CSS. It makes HTML and CSS code more orgranized.

Concepts and Usage #

Don’t worry if you don’t understand it at first. There are examples later on.

HTML Demo #

<nav> is a block, which contains the elements <ul>, <li> and <a>. --active is a modifier.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<nav class="menu">
  <ul class="menu__list">
    <li class="menu__item">
      <a class="menu__link menu__link--active" href="/en/">Home</a>
    </li>
    <li class="menu__item">
      <a class="menu__link" href="/en/posts/">Posts</a>
    </li>
    <li class="menu__item">
      <a class="menu__link" href="/en/about/">About</a>
    </li>
  </ul>
</nav>

CSS Demo #

Online demo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
/* Horizontal list */
.menu__list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  list-style-type: none;
  padding-inline-start: 0;
}

/* Embolden the link that matches the current page */
.menu__link--active {
  font-weight: bolder;
}

SCSS Demo #

I strongly recommend SCSS because you can use the parent selector & to group together all styles of both a block and its elements. This structure clearly reflects the hierarchical relationship between them.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
.menu {
  // Horizontal list
  &__list {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    list-style-type: none;
    padding-inline-start: 0;
  }

  // Embolden the link that matches the current page
  &__link {
    &--active {
      font-weight: bolder;
    }
  }
}

Alternative: Atomic CSS #

If you find BEM too verbose or difficult to maintain, you can try atomic CSS frameworks like Tailwind CSS and UnoCSS that provide utilities (predefined classes). Developers only need to write predefined class names and don’t need to write CSS code. Here are some utilities in Tailwind CSS:

1
2
3
4
5
6
.flex {
  display: flex;
}
.flex-row {
  flex-direction: row;
}

To rewrite the previous CSS code in Tailwind CSS (online demo):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<script src="https://cdn.tailwindcss.com"></script>
<script>
  tailwind.config = {
    corePlugins: {
      preflight: false,
    }
  }
</script>
<nav>
  <ul class="flex flex-row flex-wrap justify-between list-none ps-0">
    <li>
      <a class="font-bold" href="/en/">Home</a>
    </li>
    <li>
      <a href="/en/posts/">Posts</a>
    </li>
    <li>
      <a href="/en/about/">About</a>
    </li>
  </ul>
</nav>

Further Reading #

Tags:
comments powered by Disqus