Lazarev Alexandr Lazarev Alexandr - 4 months ago 32
CSS Question

SCSS. Reference second level ascending selector

One of the techniques to organise classes in the scope of avoiding collisions, is to extend a parent's class + add some suffix. For example:

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


From considerations of not duplicating code, in sass/scss files, one can refer a parent with the help of an ampersand -
&
, so above structure can be achieved like this:

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


Which is transfomed into:

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


But difficulties appear when one needs to get such a
css
as the result:

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


Since the main idea is not to duplicate selectors, a question appears - is there a way to reference second level parent? I know that
&&
ins't an issue but is there a way to simulate double ampersand behaviour?

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

}


Not an issue,
.a
is duplicated:

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


Also not an issue:

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

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


So, from the considerations of avoiding collisions many times classes have long names. And that is when duplicated selectors make code look scary. Imagine, that instead of
.a
selector there would be:
.custom-layers-list-panel-conatiner
.

Answer

Update: better than Original

.asgsg-dfg-fg-dsfg-sdf-g-sdfg{
  $grandparent: &;

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

and Original:

@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;
        }
  }
}

both generate

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

Is this ok ?

Comments