Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying styles for child elements of a BEM modifier

Tags:

css

bem

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*/ }
like image 459
Mike Rifgin Avatar asked Oct 01 '15 10:10

Mike Rifgin


2 Answers

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.

like image 102
Paleo Avatar answered Sep 22 '22 08:09

Paleo


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.

like image 37
Ingvi Jónasson Avatar answered Sep 25 '22 08:09

Ingvi Jónasson