【问题标题】:Specifying styles for child elements of a BEM modifier为 BEM 修改器的子元素指定样式
【发布时间】:2015-12-29 08:50:35
【问题描述】:

我有以下 BEM 样式的 Css 来定义一个简单的盒子:

.box { /*styles */ }
.box__heading {/*styles */}
.box__image { /*styles */}

我还需要能够在错误模式下显示该框,因此定义了以下修饰符:

.box--error {/*styles */}

我遇到的问题是找到一种在框处于错误模式时定义嵌套元素(例如 box__heading)样式的好方法。

我是否也在标题和父级上定义了修饰符:

 <div class="box box--error">
   <h2 class="box__heading box__heading--error"></h2>
 </div>

或者我只是在 css 中这样做:

.box--error {}
.box--error .box__heading { /* error styles*/ }

【问题讨论】:

    标签: css bem


    【解决方案1】:

    为获得最佳实践,只需在盒子容器上使用修饰符 box--error。当您处理更复杂的模块时,您不希望根据修饰符将修饰符类添加到所有需要样式的元素。

    在 Tarh 的示例中,有两个 box__heading 类。如果样式不应该保持不变,这将导致问题,否则这些样式不应该具有相同的类名。

    【讨论】:

      【解决方案2】:

      这两种方式都有效。

      在元素上带有修饰符:

      .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 的样式。

      【讨论】:

        猜你喜欢
        • 2019-09-30
        • 2018-11-06
        • 2020-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-31
        • 2019-01-07
        相关资源
        最近更新 更多