Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCSS. Reference second level ascending selector

Tags:

css

sass

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. Another reason of avoiding duplicated classes is that if parent class is changed, it should be changed everywhere. Yes, nowadays it's quite trivial task with some specific tools, but it's still remains a place where mistakes can appear.

like image 397
Alexandr Lazarev Avatar asked Jul 14 '16 17:07

Alexandr Lazarev


People also ask

What is &__ in SCSS?

The & is a special selector invented by SCSS which is used in nested selectors to refer to the outer selector . It simply means that it will be replaced with the outer selector when compiling to CSS.

What is @extend in SCSS?

Sass @extend Directive The @extend directive lets you share a set of CSS properties from one selector to another. The @extend directive is useful if you have almost identically styled elements that only differ in some small details.


1 Answers

Update: better than Original

.a{
  $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;
}
like image 188
Ankit Singh Avatar answered Oct 10 '22 22:10

Ankit Singh