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

随声附和 提交于 2019-12-23 12:58:35

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/25625103/less-what-is-the-purpose-of-after-a-nested-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!