I have the following sass code:
.class{
    label{
        color:#fff;
        .disabled &{color:#333; }
    }
}
which outputs
.disabled .class label
Is there a way to output the parent selector without any grandparent selectors being included? Like so:
.disabled label
                Sass lets you reference the parent selector of a nested rule using the ampersand (&) symbol –– it's one of Sass' most useful features!
The parent selector, & , is a special selector invented by Sass that's used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.
The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.
In Less, the parent selectors are denoted by &(ampersand) operator. The parent selectors of a nested rule are represented by & operator and is most commonly used when applying a modifying class or pseudo-class to an existing selector.
There's no way I know of in SASS to pick and choose from ancestor selectors when using a parent reference. With your code, though, a little reorganization can get you the same result:
label {
    .class & {
        color: #fff;
    }
    .disabled & {
        color:#333;
    }
}
Compiles to:
.class label {
  color: #fff; }
.disabled label {
  color: #333; }
                        Even though hopper is not enterly wrong, you can actually select grand-parent with variables.
You can achieve what you want with this:
.class{
    label{
        color:#fff;
        $selector: nth(&,1);
        $direct-parent: nth($selector, length($selector));
        @at-root #{$direct-parent} {
          .disabled &{color:#333; }
        };
    }
}
Which will generate this css:
.class label {
  color: #fff;
}
.disabled label {
  color: #333;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With