【问题标题】:How to select nth-child inside Element BEM Scss如何在 Element BEM Scss 中选择 nth-child
【发布时间】:2019-03-09 15:02:49
【问题描述】:

我正在使用 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>

我的 BEM Scss 我添加了 nth-child 3rd element 无效的子元素:

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

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

【问题讨论】:

标签: sass bem


【解决方案1】:

您在 .bookearly-container__row(CSS 示例中的第 4 行)中使用了子组合器 (&gt;),而唯一的直接子组合器是 .bookearly-container__col

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-10-26
    • 2013-04-04
    • 2011-09-03
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    相关资源
    最近更新 更多