为BEM修改器的子元素指定样式

时间:2015-10-01 10:26:50

标签: css bem

我有以下BEM样式Css来定义一个简单的框:

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

我还需要能够在错误模式下显示该框,因此定义了以下修饰符:

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

我遇到的问题是找到一种很好的方法来定义嵌套元素的样式,例如当框处于错误模式时的box__heading。

我还要在标题和父级上定义修饰符:

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

或者我只是在css中执行此操作:

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

2 个答案:

答案 0 :(得分:6)

这两种方式都有效。

在元素上使用修饰符:

.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设置样式。

答案 1 :(得分:2)

最佳做法是在盒子容器上使用修饰符box--error。当您处理更复杂的模块时,您不希望根据修改器向所有需要样式的元素添加修饰符类。

在Tarh的例子中,有两个box__heading类。如果样式不应该保持其他方式,这将导致问题,这些应该只是没有相同的类名。

相关问题