所以我有以下BEM课程:
.block
.block--modified
.block__child
现在从我所看到的,大多数人都会像修改后的.block
那样命名孩子:
.block--modified__child
我认为这是有道理的,但有一个原因你不能这样命名:
.block__child--modified
我认为这看起来更好并且使修改更加孤立/明确,我也喜欢这样,因为那时你可以有多个修改后的子项,它们不依赖于被修改的父项,即
我们可以拥有.block
和.block .block--modified
元素。
两者都可以.block__child
和.block__child--modified
仍然遵循命名约定,但会使子元素(已修改或未修改)更灵活。
更好的例子说我有以下课程:
.alert
.alert--warning
.alert--urgent
.alert__call-to-action
.alert__call-to-action--warning
我想按如下方式布局我的HTML:
<div class="alert">
<button class="alert__call-to-action">
Action! (No Modifier)
</button>
</div>
<div class="alert alert-warning">
<button class="alert__call-to-action alert__call-to-action--warning">
Action! (Warning Modifier)
</button>
</div>
<div class="alert alert-urgent">
<button class="alert__call-to-action alert__call-to-action--warning">
Action! (Warning Modifier)
</button>
</div>
因此,您会看到我想在.alert__call-to-action--warning
和.alert--warning
中重复使用.alert--urgent
修饰符两次,因为出于任何理由,样式是相同的。这是否有意义我可以看到它使修饰符更有用?
我们有没有理由不这样做?对不起,如果有更好的发布地点,请告诉我。
答案 0 :(得分:2)
实际上BEM方法学说你不应该在元素命名中反映块修饰符。在这种情况下使用嵌套。
见https://en.bem.info/faq/#why-should-i-avoid-using-nested-selectors
的第二段这很重要,因为:
因此,如果你使用修饰符反映在元素命名中,那么处理起来就会困难得多。
答案 1 :(得分:0)
我认为这是有道理的,但有一个原因你不能这样命名:
.block__child--modified
是的,修饰符需要附加到它修改的内容上。
如果您有块状态,则将修改器附加到块:
.message--warning
如果您有元素的状态,则将修饰符附加到元素:
.widget__content--expanded
如果你试图混合两者,意思就会丢失:
//this is a message that is in the warning state
.message--warning
//this is a heading of a message. The heading is in the warning state
.message__heading--warning
因此,您会看到我想在
.alert__call-to-action--warning
和.alert--warning
中重复使用.alert--urgent
修饰符两次,因为无论出于何种原因,样式都是相同的。
不要混合和匹配修饰符
这是否有意义我能看到它使修饰符更有用?
您可以使用这种无效的BEM使用来保存一些CSS字节,但这种微优化从未成为BEM的目标。
在我看来,你拥有的不是一组带修饰符的块。你看起来像是一系列继承自类似基块的块。
原始CSS不允许将这种继承显式化,这是不幸的。但是,使用预处理器可以。我将在这个例子中使用LESS。
不要定义.alert
,.alert--warning
和.alert--urgent
,而是考虑制作三个单独的块:
.alert {
..default styles..
&__call-to-action {
..default styles..
}
}
<子> warning.less 子>
@import (reference) 'alert';
.warning {
.alert;
..override styles..
&__call-to-action {
..override styles..
}
}
<子> urgent.less 子>
@import (reference) 'warning';
.urgent {
.warning;
..override styles..
&__call-to-action {
..override styles..
}
}
请注意,urgent
是warning
,warning
是alert
。定义这样的类允许您在HTML中使用描述性名称:
<div class="warning">
<button class="warning__call-to-action" ...>...</button>
</div>
并允许您充分利用您的样式,因为您只需覆盖少数更改的属性。
当然,整个示例依赖于能够使用预处理器来减少您编写的CSS数量。编写原始CSS更加冗长。