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

时间:2018-10-04 09:07:59

标签: sass bem

我正在使用BEM Scss解释一下如何在nth-child元素内进行选择。

我尝试使用以下格式,但对我而言无效

<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 3rd元素children元素:

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

能否请您解释一下如何选择?预先感谢。

1 个答案:

答案 0 :(得分:0)

您正在>(CSS示例中的第4行)中使用子组合器(.bookearly-container__row),并且唯一的直接子项是.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
      }
    }
  }
}
相关问题