BEM

BLOCK
ELEMENT
MODIFIER

BEM

"[...] is a smart way of naming your CSS classes to give them more transparency and meaning to other developers. They are far more strict and informative, which makes the BEM naming convention ideal for teams of developers on larger projects that might last a while." 

- http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/
.block{}
.block__element{}
.block--modifier{}

.person{}
.person--female{}
.person--male{}
.person__hand{}
.person__hand--left{}
.person__hand--right{}

The RULES

  • Well named top-level "components/blocks"
  • Do not use Tag names in selectors
  • Do not cascade styles (unless using modifier)
  • Use modifiers instead of pseudo-selectors (--last instead of :last-child)
  • When using modifiers, include both component & modifier in HTML: "person person--female"Create special js- classes for Javascript
  • Global "state" classes (.is-active) which each component can implement.

Real Example (SASS)

.nav {}
  .nav__item {
    &.is-active {}
  }
  .nav__item--first {}
  .nav__item--last {}
  .nav__label {}
  .nav--horizontal {
    .nav__item {}
    .nav__label {}
  }
  .nav--vertical {
    .nav__item {}
    .nav__label {}
  }
  

Real Example (HTML)

<nav class="nav nav--horizontal">
  <div class="nav__item nav__item--first is-active">
    <div class="nav__label">Label1</div>
  </div>
  <div class="nav__item">
    <div class="nav__label">Label2</div>
  </div>
  <div class="nav__item nav__item--last">
    <div class="nav__label">Label3</div>
  </div>
</nav>

PROS

  • Modular Components
  • Decouples JS from presentation
  • Less likely to collide with selectors accidentally named the same in other parts of the code
  • Autocomplete-friendly
  • Quick hacks stand out
  • Writing HTML while defining CSS structure
  • Avoids other pieces of code overriding your styles

CONS

  • "There are only two hard things in Computer Science: cache invalidation and naming things" -Phil Karlton
  • As more custom cases appear, original code needs to be refactored to be more generic (requires a complete understanding of uses of the component throughout the code)
  • Verbose and you have to on-ramp new developers to the system

Helpful things that help

  • One component per Sass file
  • Continue indenting sub elements, but not nesting them
  • Use partials & mixins for reusable components (html, grid systems)
  • Shorthand global styles for things like: width, visibility, text layout
  • Do majority of typographic styling directly on HTML elements (h1, p, ul, li)
  • Developers MUST collaborate when designing or refactoring components (Pair Programming FTW)

SLIDE__CONTENT--THANKS

bem

By tdreyno

bem

Naming things is hard :(

  • 1,970