简体   繁体   中英

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.

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;     
    }
}

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM