我有以下BEM样式Css来定义一个简单的框:
.box { /*styles */ }
.box__heading {/*styles */}
.box__image { /*styles */}
Run Code Online (Sandbox Code Playgroud)
我还需要能够在错误模式下显示该框,因此定义了以下修饰符:
.box--error {/*styles */}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是找到一种很好的方法来定义嵌套元素的样式,例如当框处于错误模式时的box__heading.
我还在标题和父级上定义修饰符:
<div class="box box--error">
<h2 class="box__heading box__heading--error"></h2>
</div>
Run Code Online (Sandbox Code Playgroud)
或者我只是在css中这样做:
.box--error {}
.box--error .box__heading { /* error styles*/ }
Run Code Online (Sandbox Code Playgroud)
这两种方式都有效.
在元素上使用修饰符:
.box__heading--error {
}
Run Code Online (Sandbox Code Playgroud)
或者级联:
.box--error .box__heading {
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您的块可以嵌套在自身内(递归),那么您必须避免级联.例如:
<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>
Run Code Online (Sandbox Code Playgroud)
在这里你不能使用级联,因为.box--error .box__heading将样式框2.