LESS中的双&符号

gob*_*was 4 css less

我对LESS编译器中的双符号行为感到困惑.

看:

.heading {
    &&--type-small {
        font-size: 15px;
    }
}
Run Code Online (Sandbox Code Playgroud)

将编译为:

.heading.heading--type-small {
      font-size: 15px;
}
Run Code Online (Sandbox Code Playgroud)

这很好.

但.

.wrapper {
    .heading {
        &&--type-small {
            font-size: 15px;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

会产生:

.wrapper .heading.wrapper .heading--type-small {
    font-size: 15px;
}
Run Code Online (Sandbox Code Playgroud)

看起来很奇怪.没有?

是否有任何建议使这段代码的工作方式如下:

.wrapper .heading.heading--type-small {
    font-size: 15px;
}
Run Code Online (Sandbox Code Playgroud)

谢谢=)

Mar*_*jak 7

在嵌套规则中使用&符时会发生什么情况是在输出选择器中忽略默认嵌套结构,并且&符号充当外部选择器的完整列表的占位符,并且只会将所有父规则一直插入到层次结构的顶部(上面所有嵌套级别的"路径")......没有办法解决这个问题.

所以使用第一个 - &将只是将嵌套选择器连接(连接)到外部选择器的整个列表(看起来好像只是将它添加到父选择器中)并充当组合器 - 请参阅lescss.org上的"嵌套规则".但是当你使用第二个&符号时 - 你的选择器最终会再次包含所有外部规则 - .wrapper之间的所有规则现在将被添加两次.所以,这种行为并不奇怪.另请参阅我对这个问题的回答:" 如何用LESS引用前两个元素/标签/类?" 而对于更多功能,&请参阅下面的七阶段-max的评论.或者找一些&被用作"路径"占位符的例子lescss.org上的"高级用法".

对你的具体例子:

我不完全确定你为什么要在类名中重复单词"header" .header--type-small,如果你使用它除了一个名为.header... 的类之外我会使用其他类.type-small,如:

.wrapper {
    //style for the wrapper
    .heading{
        //general style for the heading
        &.type-small {
           //style for the heading with class .type-small
           font-size: 15px;
        }
        &.type-large {
           //style for the heading with class .type-large ... and so on
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出CSS:

.wrapper .heading.type-small {
  font-size: 15px;
}
Run Code Online (Sandbox Code Playgroud)

但是如果你因某些特殊原因真的需要重复名字的整个长串......你可以这样做:

.wrapper {
    //style for the wrapper
    .heading {
        //general style for the heading
        &.heading--type{
            &-small {
               //style for the heading with class .type-small
               font-size: 15px;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出CSS:

.wrapper .heading.heading--type-small {
    font-size: 15px;
}
Run Code Online (Sandbox Code Playgroud)