2013-07-24 94 views
24

在Sass中有沒有使用&符號來選擇直接父項,而不是整個組的父項選擇器的方法?例如:薩斯&符,選擇免費父母?

.wrapper{ 
    background-color: $colour_nav_bg; 
    h1{ 
     color: $colour_inactive; 
     .active &{ 
      color: red; 
     } 
    } 
} 

編譯爲:

.wrapper h1{ 
    color: grey; 
} 

.active .wrapper h1{ 
    color: red 
} 

但我真正想要的是:

.wrapper .active h1{ 
    color: red; 
} 

就是寫SCSS像這樣唯一的選擇?

.wrapper{ 
    background-color: $colour_nav_bg; 
    h1{ 
     color: $colour_inactive; 
    } 
    .active h1{ 
     color: red; 
    } 
} 

的HTML看起來像這樣:

<ul class="wrapper"> 
    <li class="active"> 
     <h1>blah</h1> 
    </li> 
</ul> 
+0

我不認爲這樣有離開相同的另一種選擇,U有你的問題本身:) – Chandrakant

+0

內解決它只是似乎更好讓活動狀態嵌套在h1中,儘管我想問問。謝謝 –

+0

是的,這可以解決。我以爲你只是希望SASS解決方案與現有的HTML:)無論如何 - 在 – Chandrakant

回答

4

在撰寫本文時,沒有薩斯選擇了直接父,而不是一個元素的根父。有&其中(如你所知)選擇根父。也有%placeholder selectors,它隱藏了一條規則,直到它被extended

Sass是open-sourced,所以你可以貢獻一個新的「直接父母」選擇器。

+0

caryy現在這一切都改變了,現在我們有SASS 3.3? – jeremyhoover

+1

v3.3添加@ at-root選擇器,該選擇器編譯爲根父級選擇器。'@ at-root .active&{color:red; }'是close(編譯爲'.active .wrapper h1 {color:red;}',但不是OP所要求的。 – KatieK

6

您可以變通今天這個與周圍像這樣的一個mixin:

@mixin if-direct-parent($parent-selector) { 
    $current-sequences: &; 
    $new-sequences:(); 

    @each $sequence in $current-sequences { 
    $current-selector: nth($sequence, -1); 
    $prepended-selector: join($parent-selector, $current-selector); 
    $new-sequence: set-nth($sequence, -1, $prepended-selector); 
    $new-sequences: append($new-sequences, $new-sequence, comma); 
    } 

    @at-root #{$new-sequences} { 
    @content; 
    } 
} 

由於&基本上是一個列表的列表,你可以使用列表功能(nthset-nthjoinappend)創建你想要的選擇器序列。然後使用@at-root在根級別輸出新的選擇器。這裏是你如何使用它:

.grandparent-1, 
.grandparent-2 { 
    color: red; 

    .child { 
    color: blue; 

    @include if-direct-parent('.parent') { 
     color: green; 
    } 
    } 
} 

這將輸出:

.grandparent-1, 
.grandparent-2 { 
    color: red; 
} 
.grandparent-1 .child, 
.grandparent-2 .child { 
    color: blue; 
} 
.grandparent-1 .parent .child, .grandparent-2 .parent .child { 
    color: green; 
} 
+0

是否可以使用多個父類(因爲在我的情況下,我有幾個父類我將不得不應用這個混合? –

+1

@KarlRegensburger是的,你可以這樣做:'@include if-direct-parent('。parent-1 .parent-2 .parent-3'){...}'和這應該是這樣的結果:'.grandparent .parent-1 .parent-2 .parent-3 .child {...}' – myajouri

-2

我常常想你要問什麼,它是一個沒有去。我聽說你可以在Stylus中做那種事情。但還有一件事你可以嘗試使用@at-root來傳送到你的嵌套樹之外。例如:

.wrapper{ 
    h1{ 
     @at-root .wrapper .active h1 { 
      color: red; 
     } 
    } 
} 

這應該編譯到以下幾點:

.wrapper .active h1 { 
    color: red; 
} 

的好處是你保持你的選擇它在邏輯上是有道理的爲組織目的的嵌套結構。

4

你需要用@在根內容{}

.wrapper { 
    h1 { 
     @at-root { 
      .wrapper .active h1 { 
       color: red; 
      } 
     } 
    } 
}