【问题标题】:sass colon vs ampersand colonsass 冒号 vs & 冒号
【发布时间】:2021-10-21 07:51:12
【问题描述】:

我正在使用 sass 来设置元素,我对 :&: 以及何时使用它们感到困惑。

有什么区别?我们什么时候应该使用哪一个?

.root{

    :first-child{
        color: green;
    }
    
    &:first-child{
        color: green
    }
}

哪一个适合选择root容器的第一个孩子

【问题讨论】:

  • FWIW,我认为这个问题与标记的副本有点不同,因为它还处理关于 :first-child 伪类的混淆。关于“哪个适合选择根容器的第一个孩子”,答案是都不——第一个将输出无效的 CSS,第二个将获得 的第一个孩子是 .root。在 CSS 中,您想要的是 .root > *:first-child - 如果需要,您可以通过嵌套在 SCSS 中实现。

标签: html css sass


【解决方案1】:

ampersand & is the "parent selector" in Sass,并将遵循它的规则附加到包含父范围。但是,您拥有的任何一条规则都不起作用。第一个……

.root{
    :first-child{
        color: green;
    }
}

...将渲染到 CSS...

.root :first-child{
    color: green;
}

...这将是无效的 CSS,因为 :first-child pseudo-class 期望附加到实际的 CSS 选择器。

第二个……

.root{
    &:first-child{
        color: green
    }
}

...将呈现为 CSS...

.root:first-child{
    color: green
}

...但是该规则等同于“.root 班级的所有孩子中的第一个应该有绿色”,这不是您想要的。

对于你想要的——“选择根容器的第一个孩子”,你会想要这个 CSS:

.root > *:first-child {
  color: green;
}
<div class="root">
  <p>some content</p>
  <div>
    <ul>
      <li>some</li>
      <li>other</li>
      <li>content</li>
    </ul>
  </div>
</div>

...等同于“类为.root 的容器中任何类型的第一个直接后代。这可以用 sass 几种不同的方式重写;使用完全嵌套,您可以将其写为

.root {
    >* {
        &:first-child {
            color: green;
        }
    }
}

...但我可能会将其简化为...

.root {
    >*:first-child {
        color: green;
    }
}

【讨论】:

    【解决方案2】:

    原来没有: vs &amp;:

    而是,有效的是&amp;:

    &:first-child{
        color: green
    }
    

    如下所示,: 没有&amp; 是无效的

    :first-child{
        color: green;
    }
    
    //this one is an invalid code and doesn't work
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-04
      • 2019-09-14
      • 2012-09-25
      • 1970-01-01
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多