2017-05-18 82 views
1

我有一些青菜,看起來像這樣薩斯條件符號

.activities { 
    border: 1px solid green; 

    .activity { 
    background-color: red; 

    &:first-child { 
     background-color: yellow; 
    } 
    } 
} 

我想.activity元素是第一個孩子是黃色的,只有當與.activities類的父元素不也有類.events

在下面的例子中,第一.activity元素應該有background-color: red

<div class="activities events"> 
    <div class="activity">one</div> 
    <div class="activity">two</div> 
    <div class="activity">three</div> 
</div> 

有沒有否定這個第一子樣式時.activities元素也有一個.events幹法?

或者這是最簡單的方法:

.events .activity:first-child { 
    background-color: red; 
} 
+0

我認爲最簡單/最乾淨的方式。你也可以使用':not'選擇器,但這會更復雜。 – TylerH

回答

1

使用:not選擇應用黃色背景當活動元素不具備的事件類。

.activities { 
    border: 1px solid green; 

    .activity { 
     background-color: red; 
    } 

    &:not(.events) { 
     .activity:first-child { 
      background-color: yellow; 
     } 
    } 
} 

這種方法有助於減少重複。如果你突然決定活動應該是藍色而不是紅色,你只需要在一個地方改變它,而不是兩個。

https://developer.mozilla.org/en/docs/Web/CSS/:not

1

我很無聊,想看看我是否能保持只是一個activity子內的所有activity風格和與此想出了 - 雖然我不建議在彌敦道的回答用這個,因爲這真的是毫無意義的過頂的解決方案:

.activities { 
    border: 1px solid green; 

    .activity { 
    background-color: red; 

    &:first-child { 
     @at-root #{selector-replace(&, '.activities', '.activities:not(.events)')} { 
     background-color: yellow; 
     } 
    } 
    } 
} 

如果你不想重複「活動」類,你可以緩存它作爲一個變量:

.activities { 
    $this: &; 

    border: 1px solid green; 

    .activity { 
    background-color: red; 

    &:first-child { 
     @at-root #{selector-replace(&, $this, '#{$this}:not(.events)')} { 
     background-color: yellow; 
     } 
    } 
    } 
} 

Sass走得太遠了嗎?