Search code examples
csssassselectorparentancestor

Sass selector that checks if a class is on any ancestor


Is it possible to write a Sass selector that targets an element which has an ancestor that has a certain class applied?

<div class="fruit">
    <div class="tree">
        <div class="apple">
            <div class="seed">I want this to go red.</div>
        </div>
    <div>
    <div class="bush">
        <div class="raspberry">
            <div class="seed">I don't want this to go red.<div>
        </div>
    <div>
<div>

is it possible to write some kind of Sass like this?

.seed :ancestor-selector(.tree) {
    color: red;
}

...and have the "I want this to go red" actually turn red?

Here is a pen you can play with to try and make it work: https://codepen.io/timrhaynes/pen/xxGNppx


Solution

  • Yes it is. You can use & like this:

    .seed {
        .tree & {
            /** Wow! I'm seed in tree! */
            color: red;
        }
    }
    

    You can read more about Parent Selector in Sass documentation.