vakslji
vakslji

Reputation: 51

Referencing top level selector with additional class in nested Sass tree

I was using css crush for years and recently came to scss. There it was a great way to add specific property to any nested element based on additional class of the top level parent element.

<div class="someDivClass">
    <ul class="someULclass">
        <li>Text lorem ipsum</li>
        <li>Text ipsum lorem
            <ul class="someULclass2">
                <li>Text lorem ipsum</li>
                <li>Text ipsum lorem</li>
            </ul>   
        </li> 
    </ul>
</div>

Css would go something like this....

.someDivClass {
    ul.someClass {
        fewUlporpertis: values;
        li {
          fewLIporpertis: values;
          ul.someULclass2 {
              fewUlporpertis: values;
              li {
                  fewLIporpertis: values;
              }
          }
        }
    }
}

Now if i have...

<div class="someDivClass additionalClass">
    .....
</div>

I can do this...

.someDivClass {
    ul.someClass {
        fewUlporpertis: values;
        li {
          fewLIporpertis: values;
          ul.someULclass2 {
              fewUlporpertis: values;
              li {
                  fewLIporpertis: values;
                  .additionalClass& {
                      color: red;
                  }
              }
          }
        }
    }
}

That would give me this output...

.additionalClass.someDivClass ul.someClass li ul.someULclass2 li {color: red;}

Is there a way to do the same within SASS? Sorry if this is documented, all I could find is for referencing immediate parent, not a top level one.

Or to ultra simplify the question....

Why this doesn't work..

.topParent& {color: red;}

..?

Upvotes: 5

Views: 2140

Answers (1)

sschoepke
sschoepke

Reputation: 51

To avoid targeting the immediate parent, you should use the @at-root directive (introduced in Sass 3.3) to traverse back to the root of the document:

.someDivClass {
    ul.someULclass {
        li {
            ul.someULclass2 {
                li {
                    @at-root .additionalClass#{&} {
                        color: red;
                    }
                }
            }
        }
    }
}

Which would output to:

.additionalClass.someDivClass ul.someULclass li ul.someULclass2 li { color: red; }

See Demo

Upvotes: 5

Related Questions