如何在 Element BEM Scss 中 select nth-child

How to select nth-child inside Element BEM Scss

我正在使用 BEM Scss,请解释如何在第 n 个子元素中 select。

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

<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>

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

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

能否解释一下如何 select?提前致谢。

您正在 .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
    }
  }
}

如果您出于某种原因依赖子组合器 (>),您可以将其嵌套在 &__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
      }
    }
  }
}