如何在 Element BEM Scss 中选择 nth-child

B.V*_*mar 5 sass bem

我正在使用 BEM Scss 请解释如何在第 n 个子元素中进行选择。

我尝试了以下格式,但它对我不起作用

<div class="bookearly-container" >
    <div class="row bookearly-container__row">
        <div class="col-xs-12 col-md-4 bookearly-container__col">
            <div class="bookearly-container__discountcontainer">
            </div>
            <div class="bookearly-container__discountcontainer">
            </div>
            <div class="bookearly-container__discountcontainer">
            </div>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我的 BEM Scss 我添加了 nth-child 第三个元素子元素,但该元素不起作用:

.bookearly-container {
    &__row {
        margin-bottom: 4.6rem;
        & > :nth-child(3) {
            &__discountcontainer {  -- this element not selected
                &:before {
                    display: none;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

能解释一下如何选择吗?提前致谢。

Cod*_*ace 2

>您正在内部使用子组合器 ( ) .bookearly-container__row(CSS 示例中的第 4 行),并且唯一的直接子级是.bookearly-container__col

如果您想定位.bookearly-container__discountcontainer元素,则需要稍微调整选择器嵌套。

尝试将@debug指令与&选择器结合使用来查看您实际选择的内容,当您没有其他线索时这会很有帮助。

这是解决该问题的直接建议:

.bookearly-container {
  @debug &; // .bookearly-container

  &__row {
    @debug &; // .bookearly-container__row
  }

  &__discountcontainer:nth-child(3) {
    @debug &; // .bookearly-container__discountcontainer:nth-child(3)

    &:before {
      @debug &; // .bookearly-container__discountcontainer:nth-child(3):before
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

>如果您出于某种原因依赖于子组合器 ( ),您可以将其嵌套在&__col选择器内,如下所示:

.bookearly-container {

  &__col {

    // Targeting any class ending with "__discountcontainer"
    & > [class$="__discountcontainer"]:nth-child(3) {

      &:before {
        @debug &; // .bookearly-container__col > [class$="__discountcontainer"]:nth-child(3):before
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)