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

2 回答 2

7

这两种方式都有效。

在元素上使用修饰符:

.box__heading--error {
}

或级联:

.box--error .box__heading {
}

但是,如果您的块可以嵌套在自身内部(递归地),那么您必须避免级联。例如:

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

在这里您不能使用级联,因为.box--error .box__heading会设置框 2 的样式。

于 2015-10-01T13:20:19.730 回答
2

box--error为了获得最佳实践,只需在盒子容器上使用修饰符。当您处理更复杂的模块时,您不希望根据修饰符将修饰符类添加到所有需要样式的元素。

在 Tarh 的示例中,有两个 box__heading 类。如果样式不应该保留,这将导致问题,否则这些样式不应该具有相同的类名。

于 2015-10-03T20:15:16.247 回答