Search code examples
cssnestedlessancestor

Nesting ancestor rules in LESS


I have a LESS file where I've wrapped a whole bunch of rules in a body class:

body.programme {

    #VideoWrapper {
        border: 1px solid red;
        }

    etc...

    }

However I want to change the style of #VideoWrapper if another class is present in body. I thought I might be able to do the following...

body.programme {

    #VideoWrapper {
        border: 1px solid red;

        body.inside & {
            border: 1px solid yellow;
            }

        }

    etc...

    }

Basically I'm trying to output the following CSS rules:

body.programme #VideoWrapper {
    border: 1px solid red;
}
body.programme.inside #VideoWrapper {
    border: 1px solid yellow;
}

Is this even possible in LESS without pulling the rules out of the parent body.programme wrapper?


Solution

  • I think using the ampersand selector ought to do the trick, something like this:

    body.programme {
        #VideoWrapper {
            // Your styles 
        }
        &.inside {
            #VideoWrapper {
                // Different styles 
            }
        }
    }
    

    Another approach (which alas means moving those styles out of body) might be:

    #VideoWrapper {
        // generic styles
        body.programme & {
            // special styles 
        }
        body.programme.inside & {
            // further styles 
        }
    }
    

    But that might not satisfy your OCD either.