【问题标题】:Increase specificity weight with double selector via Sass通过 Sass 使用双选择器增加特异性权重
【发布时间】:2018-05-26 15:18:00
【问题描述】:

正如 Stack Overflow in another question 和 MDN tells about the specificity of selectors 中提到的,我想通过 Sass 稍微增加我的选择器的权重以覆盖一些现有的样式。这是(编译的)CSS 的示例。

.parent .parent__child.parent__child { color: red; }

它比仅仅使用.parent .parent__child 作为选择器更具体。


我有办法通过 Sass 做到这一点,但我认为应该有更好的方法来做到这一点。我现在这样做的方式是:

.parent {
    &__child.parent__child { color: red; }
}

理想情况下,这将是最好的设置(与号必须直接相互连接,因为它不是子选择器):

.parent {
    &__child&__child { color: red; }
}

这会引发错误,并在“子”选择器之间添加一个点。 Sass documentation 没有说明这个特殊情况。关于如何实现这一点的任何想法?

编辑

我知道插值括号法,但是如果选择器在三层中更深,例如四层中的三层,该怎么办?我只希望复制它的父选择器,而不是 整个 选择器树。

【问题讨论】:

    标签: css sass


    【解决方案1】:

    在 SASS 中有一个特殊的技巧,可以使用插值括号(更多关于 herehere)将特异性加倍,因为两个相邻的 & 是无效的 SASS 语法。

    .parent {
      &__child {
        &#{&} {
          color: red; 
        }
      } 
    }
    
    // compiles to
    // .parent__child.parent__child { color: red; }
    
    // You can also do this with deeper nested elements by
    // prefacing the interpolation with the ancestor selectors:
    .parent {
      &__child {
        .some .ancestor .elements &#{&} {
          color: red;
        }
      }
    }
    
    // compiles to
    // .some .ancestor .elements .parent__child.parent__child { color: red; }
    

    对于那些偶然发现并使用 LESS 的人,允许使用双 &&

    .parent {
      &__child {
        && {
          color: red;
        }
      } 
    }
    

    【讨论】:

    • @Roy 也许您应该将选择器分解为它们自己的块,并使用父选择器作为插值的开头。 .some .ancestor .classes &#{&} { ... } 之类的东西 - 编辑答案以反映这一点。
    • 但话说回来,我写的选择器比我想写的要多。
    • @Roy 你能做的只有这么多来对抗特异性。如果您的原始选择器嵌套了 3 层或 4 层或更多层,那么可能需要重新寻址原始结构,或者您可能会考虑使用 id 进行命名空间。这有明显的缺陷,我也不建议像某些人那样使用!important
    猜你喜欢
    • 1970-01-01
    • 2015-04-02
    • 2016-03-29
    • 1970-01-01
    • 2016-05-04
    • 2019-08-19
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    相关资源
    最近更新 更多