简体   繁体   中英

Sass: Extending nested selectors

(I think I should mention this, I've only recently started using Sass/SCSS)

http://jsfiddle.net/DriftingSteps/t6kLncfm/

You can see how <strong> is inheriting the properties of the global <a> as well as the properties from nested <a> tag.

a {
    color: #09f;
    text-decoration: none;
    &:hover {
        text-decoration: underline;
        opacity: 0.6;
    }
}

ul {
    font-size: 0.85em;
    a {
        font-family: Georgia, Times, serif;
        font-style: italic;
        color: #0a3;
    }
    strong {
        @extend a;
    }
}

I have been going through http://sass-lang.com/ and I know I'm missing something. What am I doing wrong? Is there a way to inherit properties from the nested <a> only, without the use of classes on either ul a and ul strong ? Or is there a better way to do this?

You could use an extend-only selector ( % ), and extend both ul a and ul strong from that:

a {
    color: #09f;
    text-decoration: none;
    &:hover {
        text-decoration: underline;
        opacity: 0.6;
    }
}

ul {
    font-size: 0.85em;
    a {
      @extend %a;
    }
    strong {
        @extend %a;
    }
}

%a {
    font-family: Georgia, Times, serif;
    font-style: italic;
    color: #0a3;
}

You don't have to use that class and you don't have to apply it to your HTML, you can just define it and refer to it when inheriting:

a, .a {
    font-family: Georgia, Times, serif;
    font-style: italic;
    color: #0a3;
}
strong {
    @extend .a;
}

Demonstration

And of course, in this case you don't really need extend:

a, strong {
    font-family: Georgia, Times, serif;
    font-style: italic;
    color: #0a3;
}
strong {
    // other stuff
}

It seems to me that the real use case of extend isn't deep localized selectors defined together, but rather the extension of a selector defined elsewhere.

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