Lokesh Yadav
Lokesh Yadav

Reputation: 1602

Sass Ampersand nesting with pseudo selectors

Trying to utlize the SASS Ampersand to get the following css output. It is not working when we use Ampersand with inside pesudo selector.

CSS

.test:first-child .test-image { display: block; }

SASS

.test {
    &:first-child {
        display: inline-block;
        &-image {
            display: block;
        }   
    }
}

Above code basically cascading the -image with first-child.

Upvotes: 2

Views: 3020

Answers (3)

Geeky
Geeky

Reputation: 7496

If you are trying to achieve

.test:first-child .test-image { display: block; }

With your code it is getting compiled as this

.test:first-child-image {
    display: block;
}

Instead ,you can simply write it as this .

.test:first-child {
        .test-image {
            display: block;
        }   
}

Hope it helps

Upvotes: 1

davidatthepark
davidatthepark

Reputation: 1365

This is because the ampersand is just concatenating the parent with the child. If you want the compiled CSS to look like your example you need to do this:

.test {
    &:first-child &-image{
      display: block;     
    }
}

Upvotes: 4

Gerrit0
Gerrit0

Reputation: 9182

It sounds like you have mistaken how the ampersand works in Sass. The ampersand is essentially a shorthand for writing each outer selector and then adding the selector after it onto the end. As .test-image is distinct from .test, you should specify it as follows.

.test {
    &:first-child {
        .test-image {
            display: block;
        }   
    }
}

Compiles to

.test:first-child .test-image {
    display: block;
}

Upvotes: 0

Related Questions