5

I have the following BEM style Css to define a simple box:

.box { /*styles */ }
.box__heading {/*styles */}
.box__image { /*styles */}

I also need to be able to show the box in error mode so have defined the following modifier:

.box--error {/*styles */}

The problem I'm having is finding a good way to define the styles for the nested elements such as box__heading when the box is in error mode.

Do I also define modifiers on the heading as well as on the parent:

 <div class="box box--error">
   <h2 class="box__heading box__heading--error"></h2>
 </div>

or do I just do this in the css:

.box--error {}
.box--error .box__heading { /* error styles*/ }
Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111

2 Answers2

8

The two ways are valid.

With a modifier on the element:

.box__heading--error {
}

or with a cascade:

.box--error .box__heading {
}

However, if your block can be nested inside itself (recursively), then you have to avoid the cascade. For example:

<div class="box box--error">
    <h2 class="box__heading box__heading--error">Box 1</h2>
    <div class="box">
        <h2 class="box__heading">Box 2</h2>
    </div>
</div>

Here you can't use a cascade, because .box--error .box__heading would style the box 2.

Paleo
  • 21,831
  • 4
  • 65
  • 76
2

For the best practise just use the modifier box--error on the box container. When you are dealing with more complex modules you do not want to add a modifier class to all the element that need styles according the modifier.

In Tarh's example there are two box__heading classes. This would cause a problem if the styles should not remain other wise these should simply not have the same class name.

Ingvi Jónasson
  • 730
  • 8
  • 27