为 BEM 修饰符的 child 个元素指定样式
Specifying styles for child elements of a BEM modifier
我有以下 BEM 样式 Css 来定义一个简单的盒子:
.box { /*styles */ }
.box__heading {/*styles */}
.box__image { /*styles */}
我还需要能够在错误模式下显示框,因此定义了以下修饰符:
.box--error {/*styles */}
我遇到的问题是找到一种很好的方法来定义嵌套元素的样式,例如当框处于错误模式时 box__heading。
我是否也在标题和 parent 上定义修饰符:
<div class="box box--error">
<h2 class="box__heading box__heading--error"></h2>
</div>
或者我只是在 css:
中这样做
.box--error {}
.box--error .box__heading { /* error styles*/ }
两种方式都有效。
在元素上使用修饰符:
.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 的样式。
为了获得最佳实践,只需在盒子容器上使用修饰符 box--error
。当您处理更复杂的模块时,您不想根据修饰符向所有需要样式的元素添加修饰符 class。
在 Tarh 的示例中有两个 box__heading classes。如果样式不应保留,这将导致问题,否则这些样式不应具有相同的 class 名称。
我有以下 BEM 样式 Css 来定义一个简单的盒子:
.box { /*styles */ }
.box__heading {/*styles */}
.box__image { /*styles */}
我还需要能够在错误模式下显示框,因此定义了以下修饰符:
.box--error {/*styles */}
我遇到的问题是找到一种很好的方法来定义嵌套元素的样式,例如当框处于错误模式时 box__heading。
我是否也在标题和 parent 上定义修饰符:
<div class="box box--error">
<h2 class="box__heading box__heading--error"></h2>
</div>
或者我只是在 css:
中这样做.box--error {}
.box--error .box__heading { /* error styles*/ }
两种方式都有效。
在元素上使用修饰符:
.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 的样式。
为了获得最佳实践,只需在盒子容器上使用修饰符 box--error
。当您处理更复杂的模块时,您不想根据修饰符向所有需要样式的元素添加修饰符 class。
在 Tarh 的示例中有两个 box__heading classes。如果样式不应保留,这将导致问题,否则这些样式不应具有相同的 class 名称。