【问题标题】:How to select nth-child in SASS within a nested selectors如何在嵌套选择器中选择 SASS 中的第 n 个子项
【发布时间】:2017-12-11 10:18:14
【问题描述】:

在嵌套 SCSS 中使用 nth-child 时,有没有办法不重复 clip-item 类?输出应该在下面的 CSS 中。

CSS

.clip-item .group-left {
  padding: 0;
}
.clip-item .group-left:nth-child(2n+1) {
  background: blue;
}
.clip-item .group-left:nth-child(2n+2) {
  background: gray;
}
.clip-item .group-right {
  padding: 0;
}
.clip-item .group-right:nth-child(2n+1) {
  background: blue;
}
.clip-item .group-right:nth-child(2n+2) {
  background: gray;
}

我试图像下面那样做。尽管 t 有效,但我认为这不是正确的方式/干净的方式。

SCSS

.group-left {
  .clip-item & {
    padding: 0;
  }
  .clip-item:nth-child(2n+1) & {
    background: blue;
  }
  .clip-item:nth-child(2n+2) & {
    background: gray;
  }
}

.group-right {
  .clip-item & {
    padding: 0;
  }
  .clip-item:nth-child(2n+1) & {
    background: blue;
  }
  .clip-item:nth-child(2n+2) & {
    background: gray;
  }
}

我还在某些内容中使用 .group-left 和 .group-right 类,这就是我将其用作父选择器的原因。

编辑:- 每个组包装器都包装在一个剪辑项 div 中。以下是我的标记:-

<div class="clip-item">
  <div class="group-left">
  <div class="group-right">
</div>

<div class="clip-item">
  <div class="group-left">
  <div class="group-right">
</div>

【问题讨论】:

    标签: css sass


    【解决方案1】:

    如果您需要以这种方式对选择器进行分组 - 我建议使用 @at-root directive.

    @at-root 指令导致一个或多个规则在 文档的根,而不是嵌套在其父级之下 选择器。

    .group-left {
      .clip-item & {
        padding: 0;
      }
      @at-root .clip-item &:nth-child(2n+1) {
        background: blue;
      }
      @at-root .clip-item &:nth-child(2n+2) {
        background: gray;
      }
    }
    
    .group-right {
      .clip-item & {
        padding: 0;
      }
      @at-root .clip-item &:nth-child(2n+1) {
        background: blue;
      }
      @at-root .clip-item &:nth-child(2n+2) {
        background: gray;
      }
    }
    

    Codepen demo(查看编译后的 CSS)

    另外,this CSS-tricks post 可能会有所帮助:

    &amp; 不允许您有选择地向上遍历嵌套 选择器树到某个地方并且只使用一小部分 您要使用的已编译父选择器。


    顺便说一句:

    即使它有效,但我认为这不是正确的方法

    实际上,您的 SCSS 目前没有生成请求的 CSS。

    【讨论】:

    • 您好丹尼尔,非常感谢您的回复和建议。我错过了告诉每个组包装器都包装在一个剪辑项 div 中。我已经尝试了您提供的代码,但不起作用。我编辑了我的帖子并添加了我当前的标记。对此感到抱歉。
    • @AlexandriaMiguel - 我用您编辑的标记更新了 Codepen,但保留了 SASS,因为编译后的 CSS 完全符合您的要求
    猜你喜欢
    • 2014-01-20
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多