Search code examples
cssbem

Specifying styles for child elements of a BEM modifier


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*/ }

Solution

  • 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.