2013-10-07 33 views
2

我對LESS編譯器中的雙符號行爲感到困惑。雙連字符LESS

看:

.heading { 
    &&--type-small { 
     font-size: 15px; 
    } 
} 

將被編譯到:

.heading.heading--type-small { 
     font-size: 15px; 
} 

並且那好。

但是。

.wrapper { 
    .heading { 
     &&--type-small { 
      font-size: 15px; 
     } 
    } 
} 

會產生:

.wrapper .heading.wrapper .heading--type-small { 
    font-size: 15px; 
} 

它看起來很奇怪。沒有?

有沒有什麼建議,使這個代碼的工作,如:

.wrapper .heading.heading--type-small { 
    font-size: 15px; 
} 

感謝=)

+1

據我所知,沒有辦法只插入外部選擇器的一部分。 – SLaks

+0

什麼時候將'&&'功能添加到LESS以及它在哪裏記錄?我沒有聽說過這個。 – zzzzBov

+1

@zzzzBov不是嵌套規則名稱(以及第二個&符號)中第一個字符的&符號基本上是整個嵌套規則路徑的佔位符 - 請參閱我的答案以獲取更多詳細信息。我相信它是在[LESS 1.3.1](https://github.com/less/less.js/blob/master/CHANGELOG.md#131)中使用&符號的其他功能引入的。根據[「高級用法&」](http://lesscss.org/#-advanced-usage-of- &)記錄。 –

回答

6

什麼,當你在一個嵌套規則中使用的符號的情況是,默認的嵌套結構得到的忽略輸出選擇器,and符號作爲作爲外部選擇器的完整列表的佔位符,並且只會將所有父規則一直插入層次結構的頂部(上面所有嵌套級別的「路徑」)...否解決方法。

因此,在使用的第一個 - &將剛剛加入(串連)嵌套選擇器外選擇(表現爲如果它只是將其添加到父選擇器),並作爲一個組合子的整個列表 - 看到"Nested rules"在lescss .ORG。但是當你使用第二個符號時 - 你的選擇器將最終再次包括所有外部規則 - .wrapper以及其間的所有規則現在將被添加兩次。所以,這種行爲並不奇怪。另請參閱我對此問題的回答:How to refer to two previous elements/tags/classes with LESS?」以及&的一些更多功能,另請參閱下面的七個階段 - 最多的評論。或者在lescss.org上找到&作爲"Advanced Usage of &"下的「路徑」佔位符的示例。

和你具體的例子:

我不完全知道爲什麼要重複在類名.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 
     } 
    } 
} 

與輸出CSS:

.wrapper .heading.type-small { 
    font-size: 15px; 
} 

但如果你真的真的需要整個長字符串用某種特定原因的反覆名字......你可能只是做這樣的事情:

.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; 
      } 
     } 
    } 
} 

與輸出CSS:

.wrapper .heading.heading--type-small { 
    font-size: 15px; 
} 
+1

「這兩個&只是有非常不同的功能」 - 這是不正確的,事實上,無論您使用多少次。 &符號始終指「外部選擇器的完整列表」,從不指「最近的父級」(請參見[Parent-Selectors](https://github.com/less/less.js/wiki/Parent-Selectors) ,[Appender](https://github.com/SomMeri/less4j/wiki/Less-language-Nesting#appender))。嘗試以下示例以進入'&'擴展機制:1.'a {b {c&{ - : - }}}'2.'a,b {c,d {&+&{ - : - }} }' –

+0

典型的混淆之處通常是:「使用'&並不明顯,也會取消所有外部選擇器的默認預先設置」,所以對於基本的'a {b {&c { - : - }} }'它可能看起來像'&'只是最近父母的同義詞 - 但事實並非如此。 –

+0

當我們進行「詳細解釋」時,恐怕我們必須說1)和2)(以及「在規則名稱中使用&<<作爲第一個字符>它做2件事情」)。否則,我們只是把事情推向錯誤的方向,當@ gobwas將面臨類似'a {b {c&{ - : - }}}'的事情時,他又震驚了(例如見https://github.com/less/less .js/issues/1575) –