Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Sass, How do you reference the parent selector and exclude any grandparent?

Tags:

sass

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
like image 364
Cato Johnston Avatar asked Jul 27 '12 03:07

Cato Johnston


People also ask

Which symbol is used to refer parents selector in SASS?

Sass lets you reference the parent selector of a nested rule using the ampersand (&) symbol –– it's one of Sass' most useful features!

Is there a SASS parent selector?

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.

How do I use parent selector in CSS?

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.

How do you refer to a parent in nested rules inside less?

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.


2 Answers

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; }
like image 126
hopper Avatar answered Oct 04 '22 02:10

hopper


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;
}
like image 29
Kiss Avatar answered Oct 04 '22 02:10

Kiss