Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append the parent selector to the end with Sass

Tags:

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?

like image 643
José Tomás Tocino Avatar asked Apr 19 '13 15:04

José Tomás Tocino


1 Answers

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 {
  /* ... */
}
like image 198
cimmanon Avatar answered Sep 20 '22 14:09

cimmanon