In Sass, how do you reference the parent selector and exclude any grandparents?

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 including grandparent selectors? For instance:

.disabled label
+5
source share
2 answers

In SASS, I don’t know select and select from ancestor selectors when using a parent link. With your code, however, a small reorganization might get the same result:

label {
    .class & {
        color: #fff;
    }

    .disabled & {
        color:#333;
    }
}

The following will compile:

.class label {
  color: #fff; }
.disabled label {
  color: #333; }
+5
source

The parent selector is always a reference to the entire allowed selector from the previous nesting level. There is no concept of “parent” or “grandmother,” especially when clutching selectors or using a parental selector at the end mix water.

: , .

Sass 3.4, , & . ( ..).

, :

@function selector-slice($sel, $start: 1, $end: -1) {
    $collector: ();
    @each $s in $sel {
        // calculate our true start and end indices when given negative numbers
        $_s: if($start > 0, $start, length($s) + $start + 1);
        $_e: if($end > 0, $end, length($s) + $end + 1);
        $c: ();
        @for $i from $_s through $_e {
            $c: append($c, nth($s, $i));
        }
        // prevent duplicates from creeping in
        @if not index($collector, $c) {
            $collector: append($collector, $c);
        }
    }
    @return $collector;
}

/* complex example */
.one-a, .one-b {
    two {
        three {
            color: red;

            &:before {
                @at-root #{selector-slice(&, 2, 3)} {
                    color: green;
                }
            }
        }
    }
}

/* your example */
.class {
    label {
        color:#fff;
        @at-root #{selector-slice(&, -1, -1)} {
            .disabled & {
                color:#333;
            }
        }
    }
}

:

/* complex example */
.one-a two three, .one-b two three {
  color: red;
}
two three:before {
  color: green;
}

/* your example */
.class label {
  color: #fff;
}
.disabled label {
  color: #333;
}

, , .

.one-a, .one-b {
    two {
        three {
            color: red;

            &:before {
                @at-root #{selector-slice(&, 3, 2)} {
                    color: green;
                }
            }
        }
    }
}

:

.one-a two three, .one-b two three {
  color: red;
}
three:before two {
  color: green;
}

: Sass (/ ..)

selector-replace , , , .

.class {
    label {
        color:#fff;
        @at-root #{selector-replace(&, '.class', '.disabled')} {
            color:#333;
        }
    }
}

:

.class label {
  color: #fff;
}
.disabled label {
  color: #333;
}
-1

All Articles