如何使用Sass正确使用BEM

3 html css sass bem

我开始使用BEM方法[BLOCK,ELEMENT,MODIFIER],我对它有疑问.

在一个名为"参与"的部分中,我有一个表单,所以:

<section class="participate">
  <form class="participate__form">
    <label for="name" class="participate__form__label"></label>
    <input type="text" id="name" name="participate__form__input"/>

  </form>
</section>
Run Code Online (Sandbox Code Playgroud)

而CSS:

.participate {
 &__form {
   // css here
 }
 &__form__label {
   // css here
 }
 &__form__input {
   // css here
 }
}
Run Code Online (Sandbox Code Playgroud)

表格中的类太大了,所以告诉我权利会深入一层:

<section class="participate">
  <form class="participate__form form">
    <label for="name" class="form__label"></label>
    <input type="text" id="name" name="form__input"/>

  </form>
</section>
Run Code Online (Sandbox Code Playgroud)

但是我该如何设计呢?

我这样使用它:

.participate {
 .form {
   // CSS HERE
   &__label {
   // CSS HERE
   }
   &__input {
   // CSS HERE
   }
 }
}
Run Code Online (Sandbox Code Playgroud)

但我真的相信这不是正确的做法.拜托,有人可以给我一个灯吗?

Ale*_*ich 6

首先,您不需要级联.participate .form.最好在同一个DOM节点上使用mix:.participate__form+ .form.

participate__form__label使用BEM方法也是错误的.使用participate__form-label,或participate-form__label,或只是form__label.

我这样做:

<section class="participate">
  <form class="participate__form form">
    <label for="name" class="form__label"></label>
    <input type="text" id="name" name="form__input"/>
  </form>
</section>
Run Code Online (Sandbox Code Playgroud)

participate块和__form元素的样式:

.participate {
  &__form {
    // outer styles here
  }
}
Run Code Online (Sandbox Code Playgroud)

form自己的风格

.form {
  &__label {
    // inner styles here for label
  }
  &__input {
    // and input customization
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您仍需要在participation上下文中对表单进行自定义,则可以使用修饰符:

.form--god-bless-participation {
  .form__label {
    // label customization
  }
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以随时随地使用您的表单,也可以将原始表单替换participate为另一个表单,甚至是form类似块.