Should module child elements be nested in module modifiers?

261 views Asked by At

When writing css using BEM if you need to make changes to a module element when it is in a sub-module do you nest the module-element in the sub-module or create a new class name for the module-element?

Creating a New Class

Creating a new class name(i.e. module--modifier__element) seems to be more in the spirit of BEM. It prevents unnecessary specificity. But it also adds a lot of extra work adding an extra class to each element within the module.

Nesting

Nesting the existing element class within the module modifier(i.e. module--modifier module__element {} will add some extra specificity but saves you a lot of work(at least for large modules) and makes the markup easier to maintain. For example if you needed to change the modifier of a module you would only have to change it one place in the markup rather than having to change it on every child element.

In addition to that if not all of the child elements change then you will have to refer to the css to figure out which child elements need a class added to them.

EXAMPLE CODE

.module {
  display: block;
  width: 90%;
  height: 2rem;
  margin: 2rem auto;
  padding: 0.5em;
  background: #fff;
  border: 2px solid #333;
}

.module--modified1 {
  background: #333;
  border: none;
}

.module--modified2 {
  background: #baa;
  border: 3px solid #8f8;
}

  .module__element {
    color: #333;
    text-align: center;
  }

  /* Option 1 */
  /* In sass this would actually be nested within the module_modified1 block */
  .module--modified1 .module__element {
    color: #fff;
  }

  /* Option 2 */
  .module--modified2__element {
    color: #fff;
    font-size: 1.3em;
  }
<div class="module">
  <div class="module__element">Module</div>
</div>

<div class="module module--modified1">
  <div class="module__element">Module Modifier 1</div>
</div>

<div class="module module--modified2">
  <div class="module__element module--modified2__element">Modulue Modifier 2</div>
</div>

1

There are 1 answers

0
Paleo On BEST ANSWER

Both options are valid. Reduce the specificity is a good practice, but make the code simple is also a good practice.

However, BEM blocks have to be context-free. If a block can be recursively included into itself, then cascades must be avoided. For example, a generic block fun-rounded-block could be recursively reused like this:

<div class="fun-rounded-block fun-rounded-block--blue-version">
    <div class="fun-rounded-block__content">
        <div class="some-block-here">
            <div class="fun-rounded-block">
                <p class="fun-rounded-block__content">element in the sub-block here</p>
            </div>
        </div>
    </div>
</div>

In this example, you cannot use a cascade for styling elements because the selector .fun-rounded-block--blue-version .fun-rounded-block__content would interfere with the sub-block.