Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

Append the parent selector to the end with Sass

Ok, suppose I have the following traditional CSS

.social-media { /* ... */ }
.social-media .twitter { /* ... */ }
.social-media .facebook { /* ... */ }
ul.social-media { /* ... */ }

So, I tried to do it like this with SCSS:

.social-media {

    /* ... */

    .twitter { 
        /* ... */
    }
    .facebook {
        /* ... */
    }

    // Here's the problem:
    ul& {
        /* ... */
    }
}

The last part does not work, because it seems like the ampersand should only appear at the beginning of a selector. Is there a workaround?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sass 3.2 and older

The only thing you can do is reverse your nesting or not nest at all: .social-media {

    /* ... */

    .twitter { 
        /* ... */
    }
    .facebook {
        /* ... */
    }
}

ul.social-media {
    /* ... */
}

Sass 3.3 and later

You can do that using interpolation and the @at-root directive:

.social-media {
    /* ... */

    // Here's the solution:
    @at-root ul#{&} {
        /* ... */
    }
}

However, if your parent selector contains multiple selectors, you'll need to use selector-append instead:

.social-media, .doodads {
    /* ... */

    // Here's the solution:
    @at-root #{selector-append(ul, &)} {
        /* ... */
    }
}

Output:

.social-media, .doodads {
  /* ... */
}
ul.social-media, ul.doodads {
  /* ... */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...