BEM修饰符子类的命名麻烦

Oti*_*ght 5 css naming conventions naming-conventions bem

所以我有以下BEM类:

.block
.block--modified
.block__child
Run Code Online (Sandbox Code Playgroud)

现在,从我所看到的大多数人会这样命名修改后的孩子.block

.block--modified__child
Run Code Online (Sandbox Code Playgroud)

我知道这是有道理的,但是否有一个原因您无法这样命名:

.block__child--modified
Run Code Online (Sandbox Code Playgroud)

我认为这样看起来更好,并使修改更孤立/更明确,我也喜欢这样,因为这样您可以拥有多个修改后的子级,而这些子级不依赖于被修改的父级

我们可以有.block.block .block--modified元素。

两者都可以具有.block__child并且.block__child--modified仍然遵循命名约定,但是使子元素(无论是否修改)都更加灵活。

举一个更好的例子,我有以下课程:

.alert
.alert--warning
.alert--urgent

.alert__call-to-action
.alert__call-to-action--warning
Run Code Online (Sandbox Code Playgroud)

我想按如下方式布置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>
Run Code Online (Sandbox Code Playgroud)

因此,您将看到我想在和中重复使用.alert__call-to-action--warning修饰符两次.alert--warning.alert--urgent因为无论出于何种原因,样式都是相同的。从我看到的意义来看,这使修饰符更加有用吗?

我们不这样做是有原因的吗?抱歉,如果有更好的发布位置,请告诉我。

tad*_*uta 5

实际上 BEM 方法说你不应该在元素命名中反映块修饰符。在这种情况下使用嵌套。

请参阅https://en.bem.info/faq/#why-should-i-avoid-using-nested-selectors的第二段

这很重要,因为:

  1. 同一块/元素上可以有很多修饰符
  2. 修饰符表示块/元素的状态,可以在运行时使用 JS 进行更改。

因此,如果您使用元素命名中反映的修饰符,则会更难处理。