【问题标题】:Overriding BEM element modifier in SASS implementation在 SASS 实现中覆盖 BEM 元素修饰符
【发布时间】:2015-04-02 13:05:03
【问题描述】:

这让我困惑了一段时间。

我们使用 Sass (SCSS) 并实现类似 BEM 的命名约定通过 lib-sass

例如,我们有:

.description {
  .title {
    color: red;
  }
}

可能有description--special 想要执行以下操作:

.description {
  .title {
    color: red;
  }

  &--special {
    .title {
      color: blue;
    }
  }
}

自然会出现特异性问题,因为预期用途是:

<div class="description description--special"></div>

有人可以建议一种足够优雅的方法吗?

目前的“最佳”建议是这样做:

.description.description--special {
  .title {
    color: blue;
  }
}

当然,至少在 lib-sass 中,这是行不通的:

.description {
  .title {
    color: red;
  }

  &.&--special {
    .title {
      color: blue;
    }
  }
}

也不是这样:

.description {
  &root: &;

  .title {
    color: red;
  }

  &.#{&root}--special {
    .title {
      color: blue;
    }
  }
}

【问题讨论】:

  • 不要在 yandex.com 之外使用 BEM。如果您不在 yandex 中工作,请不要使用它。
  • LibSass 与 Sass 不同。它比 Sass 大约落后 1-2 个版本,而您要寻找的功能仅在最新版本中可用。
  • 请注意,如果您尊重 BEM,您的 .title 应该在 .description 之外并命名为 .description__title
  • @LeBen 没错,但这正是我们不采用完整 BEM 的原因。它是 BEM + OOCSS over SMACSS-like 结构。这里的 OOCSS 部分是相关的,因为 title 是可重用的模式,不能编码到描述中(同样,这里的命名可能不是最好的)。

标签: sass bem


【解决方案1】:

使用纯 BEM 语法

HTML:

<div class="description description--special">
  <h1 class="description__title"></h1>
</div>

SCSS:

.description {
  &__title {
    color: red;
  }

  &--special &__title {
    color: blue;
  }
}

使用另一种 BEM 语法和 OOCSS

这是我使用的替代语法:

  • 组件名称
  • ComponentName.modifierName
  • 组件名称-后代名称
  • ComponentName-descendantName.modifierName
  • ComponentName.isStateOfComponent
  • nonBemPrefix-something(例如“ob-myCssObject”)

以下代码与您的代码很接近。 HTML:

<div class="Description special">
  <h1 class="ob-title"></h1>
</div>

SCSS:

.ob-title {
  font-weight: bold;
}
.Description {
  .ob-title {
    color: red;
  }
  &.special {
    .ob-title {
      color: blue;
    }
  }
}

作为第三个建议,我建议不要用 OOCSS 污染你的 BEM 规则。 HTML:

<div class="Description special">
  <h1 class="Description-title ob-title"></h1>
</div>

SCSS:

.ob-title {
  font-weight: bold;
}
.Description {
  &-title {
    color: red;
  }
  &.special &-title {
    color: blue;
  }
}

注意:您应该考虑保持 BEM 方式,使用组件 Title 而不是 CSS 对象 ob-title

【讨论】:

  • 这绝对是答案。
  • 如果我想在没有元素的情况下执行此操作怎么办?查看您的第一个示例,我希望颜色位于块上 (description),并且我想向块添加一个修饰符 以更改颜色?
  • @Botis 然后是修饰符,比如.description--special
猜你喜欢
  • 2015-11-10
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 2018-04-30
  • 2012-12-14
  • 1970-01-01
  • 2019-07-11
  • 2017-05-23
相关资源
最近更新 更多