Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LESS - what is the purpose of "&" AFTER a nested selector [duplicate]

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.& ?

like image 943
Rayjax Avatar asked Dec 26 '22 04:12

Rayjax


2 Answers

The & in Less denotes the parent selector. So wherever you put the &, it replaces it with the parent selector in the CSS, if you have a space before it.

If not, i.e., no space is given before the &, it becomes the child and appends the selector with its parent like in your case.

References:

  • Less CSS Secrets-of-the-Ampersand
  • Parent Selector
like image 196
Praveen Kumar Purushothaman Avatar answered Jan 13 '23 20:01

Praveen Kumar Purushothaman


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.

like image 33
bishop Avatar answered Jan 13 '23 19:01

bishop