Search code examples
cssless

What is the purpose of "&" AFTER a nested selector in Less


Less

.list a{
    .landscape&{
        height: 100%;
    }
}

Outputs

.landscape.list a {
  height: 100%;
}

Which means "all a tags whose parents have both .landscape and .list"

Less

.list a{
    &.landscape{
        height: 100%;
    }
}

Outputs

.list a.landscape {
  height: 100%;
}

Which means "all a tags which have class 'landscape' and whose parents have .list"

And that makes sense. But if I remove the "a" tag from those selectors, the '&' only changes the concatenation order of .list and .landscape.

What's the point? When should I use &.class and when should I use class.&?


Solution

  • The article "LESS CSS: Secrets of the Ampersand" details the difference well. I'll highlight the key uses:

    • Attach a class to an existing selector
    • Change state based on parent classes
    • Filter a nested selector to only match certain elements
    • Avoid repetition when selecting repeated elements
    • Simplify combinatorial explosions

    The latter is my favorite. I've used it to handle some crazy IE issues. Check this out:

    /**
     * Add a top border to paragraphs,
     * but remove that border when a preceding paragraph already has one.
     */
    p  {
        border-top: 1px solid gray;
        & + & {
            border-top: 0;
        }
    }
    

    I think if you can wrap your mind around what this usage of & does, all the other uses become obvious.