Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS / SCSS @extend rule selectors

Tags:

css

sass

I'm having a little problem with the @extend rule, this is what I got (focus on the h1):

.content-header {
    // CSS properties
    h1 {
        // CSS properties
    }
}

.box-header {
    // CSS properties
    h1 {
        @extend .content-header h1; // My selector problem!
        // And his own CSS properties
    }
}

So it will be:

.content-header h1, .box-header h1 {
    /* Happily sharing the same CSS properties */
}

But it seems like @extend don't like that, is any other way to write this without giving the h1 a class??

like image 659
asterk-7g Avatar asked Jun 25 '12 22:06

asterk-7g


2 Answers

Nested selectors cannot be extended - in fact, that's the syntax error that is reported by the parser. Structural comments aside (I can't think of a scenario where the above @extend relationship is warranted), this is not something that can be currently accomplished with SASS.

NB: this is, however supported by Stylus if you're open to it.

like image 66
Oleg Avatar answered Oct 18 '22 16:10

Oleg


An obvious solution whould be to define a new @mixin your-name for your .content-header h1 definitions and @include your-name within .box-header h1.

But, there is a much better solution Referencing Parent Selectors: & :

h1 {
    .content-header &,
    .box-header & {
        // CSS properties
    }
    .box-header & {
        // And his own CSS properties
    }
}

It's not obvious because the logic reverse but it's better to maintain. You are changing the definitions of h1 for a specific selector.

like image 23
Raphael Bossek Avatar answered Oct 18 '22 17:10

Raphael Bossek