5

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

TylerH
  • 20,799
  • 66
  • 75
  • 101
Rayjax
  • 7,494
  • 11
  • 56
  • 82
  • The `&` is just 'replaced' with the parent selectors. http://stackoverflow.com/questions/11724861/using-the-ampersand-sass-parent-selector-inside-nested-selectors here shows an example. – bzeaman Sep 02 '14 at 13:56

2 Answers2

7

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:

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 3
    LESS documentation: [parent selector](http://lesscss.org/features/#parent-selectors-feature) (with no space it's also a parent selector but it isn't intuitive at all, at least for me: I also thought it was an append mechanism for many months when in fact it's just a consequence of being a parent selector; the most used consequence in fact) – FelipeAls Sep 02 '14 at 14:00
  • 1
    Or in other words: `&` is *always* "parent selector(s)" with or without space before or after it. – seven-phases-max Sep 02 '14 at 15:28
4

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.

bishop
  • 37,830
  • 11
  • 104
  • 139