LESS - 在 parent 上使用带有额外 class 的 BEM 选择器来偏离

LESS - using BEM selector with extra class on parent to deviate

我有一些看起来像这样的标记 -

<div class="card">
   <div class="card__icon">Icon</div>
   <div class="card__text">Text</div>
</div>

我的造型有点像这样-

.card {
     &__icon {
        font-size: 1.75em;

         @media (min-width: 992px) {
              font-size: 2em;
          }
      }

       &__text {
          font-size: 1em;
       }
}

这很好用 - 但是父级正在切换 class .current 并且我试图使用相同的方法更改其中一种子级样式,但似乎无法获得它工作。我正在尝试这个 -

.card {
     &__icon {
        font-size: 1.75em;

         @media (min-width: 992px) {
              font-size: 2em;
          }
      }

       &__text {
          font-size: 1em;
       }

      &.current {
          // this is not working
          &__text {
              color: red;
          } 
     }
}

我可以将 &.current 中的 &__text 更改为 .card__text 并且它工作正常 - 但是我想知道是否有办法可以保留 &__text &.current 中使用 LESS 的语法。谢谢!

根据文档,parent selector & 扩展到整个父级嵌套规则,按原样获取每个嵌套规则父级并将其插入代替 `&,因此在您的情况下

.card {
     &.current {
         &__text {
             color: red;
         } 
     }
}

编译为

.card.current__text {
    color: red;
}

这不是我们想要的,因为class current__text不存在。为避免这种情况,您可以像这样在 less 规则中重新排列 class 选择器:

.card {
     .current & {
         &__text {
             color: red;
         } 
     }
}

编译为:

.current .card__text {
    color: red;
}

可以在此 codepen

中找到一个工作示例