css - SCSS。引用二级升序选择器

标签 css sass

在避免冲突的范围内组织类的技术之一是扩展父类+添加一些后缀。例如:

<div class="a">
  <div class="a__b">
  <div class="a__c">
    <span class="a__d">

出于不重复代码的考虑,在sass/scss文件中,可以通过&符号-&来引用父级,所以上面的结构可以这样实现:

.a{
 &__b{}
 &__c{}
 &__d{}

转化为:

.a__b {}
.a__c {}
.a__d {}

但是当需要得到这样一个css作为结果时,困难就来了:

.a:hover{
  color: red;  
}
.a:hover .a__b{
  color: blue;
}

由于主要思想不是复制选择器,所以出现了一个问题——有没有办法引用二级父级?我知道 && 不是问题,但有没有办法模拟双符号行为?

.a{
    &:hover{
        color: red;
        & __b { /* & -> .a:hover, but I need just .a */
            color: blue;
        }
    }

}

不是问题.a 是重复的:

.a:hover { //here
  color: red;
  .a__b { //here
    color: blue;
  }
}

也不是问题:

.a { //ok
  &:hover {
  color: red;

    .a__b { //oops, duplicated selector
      color: blue;
    }
  }
}

所以,很多时候出于避免碰撞的考虑,类的名字都比较长。这就是重复的选择器让代码看起来很可怕的时候。想象一下,代替 .a 选择器的是:.custom-layers-list-panel-conatiner。避免重复类的另一个原因是,如果更改了父类,则应在所有地方进行更改。是的,现在使用某些特定工具完成这项任务非常简单,但它仍然是一个可能出现错误的地方。

最佳答案

更新:比原来的更好

.a{
  $grandparent: &;

  &:hover{
    color: red;

    & #{$grandparent}__b {
      color: blue;
    }
  }
}

原文:

@function r-pseudo($s) {
  $string: nth(nth($s, 1), 1);
    @return str-slice($string, 0, str-index($string, ':') - 1);
}

.a{
  &:hover{
    color: red;

    & #{r-pseudo(&)}__b {
      color: blue;
    }
  }
}

都产生

.a:hover {
  color: red;
}
.a:hover .a__b {
  color: blue;
}

关于css - SCSS。引用二级升序选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38380604/

相关文章:

json - node.js sass/scss 解析器输出json

sass - 在选择器中使用它们之前在 SCSS 中剥离主题标签的变量?

javascript - 单击时重新加载多个 iframe

javascript - 粘性标题导航菜单,当我向下滚动页面时,顶部有间隙

html - 悬停时显示两件事

css - 使用 SASS 计算上边距

php - Gulp-webapp 运行 BrowserSync 和 PHP

css - @font-face 不适用于网站副本

html - 为什么我的空 div 在使用 display inline 时有宽度但会折叠?

reactjs - 使用 Rollup 和 Sass react 可摇树的组件库