2017-10-11 46 views
-2

我試圖執行某種在薩斯語義 CSS類嵌套。我想強制該部分的css代碼只能在部分中使用,以確保<section />標記在語義上應該使用。薩斯「語義」嵌套的標籤和類

但我與我的Sass文件中使用的&煩惱運行。考慮下面的html:

<section class="section-home"> 
    <h1 class="section-home__heading">Section heading</h1> 
    <p class="section-home__intro">This is some random text</p> 
</section> 

我會承擔,我可以用在薩斯下​​面的代碼,但沒有:

section { 
    &.section-home { 
    background-color: white; 
    &__heading { 
     font-size: 5rem; 
    } 
    &__intro { 
     color: grey; 
    } 
    } 
} 

薩斯使得它分爲以下CSS:

section.section-home{background-color:#fff} 
section.section-home__heading{font-size:5rem} 
section.section-home__intro{color:grey} 

而且這是不是我所期望或需要,我想:

section.section-home{background-color:#fff} 
section.section-home .section-home__heading{font-size:5rem} 
section.section-home .section-home__intro{color:grey} 

這是一個錯誤?我在這裏做錯了什麼?

+4

不,這不是一個錯誤;這就是你應該預期的。爲什麼'&'的內部和外部使用會有不同的表現? – jonrsharpe

+0

是的,好的。但是如何利用'&'?這是Sass的要點,而使用BEM不是嗎? –

+0

我想'''section.section家庭{背景色:#FFF} section.section家庭.section僞-home__heading {字體大小:5rem} section.section家庭.section僞-home__intro {顏色:灰色}'''。查看html。 –

回答

0

只需更改CSS來:

section { 
    &.section-home { 
    background-color: white; 

    .section-home { 
     &__heading { 
     font-size: 5rem; 
     } 
     &__intro { 
     color: grey; 
     } 
    } 
    } 
} 

這樣無禮的話將其解釋爲:

section.section-home

section.section-home .section-home__heading

section.section-home .section-home__intro

+0

但是會出現在多個位置但是這不會正確地創建'section.section-home {background-color:#fff}' – jonrsharpe

+0

已更改,無法正確解釋OP的需要之前:) –

0

這將解決ÿ我們的問題,但是爲什麼稱它爲「.section-」,當你可以簡單地稱它爲「.home」時,它已經被html標籤限制了。

section { 
    &.section-home { 
    background-color: white; 

    .section-home__heading { 
     font-size: 5rem; 
    } 

    .section-home__intro { 
     color: grey; 
    } 
    } 
} 
+0

你沒有解決這個問題,你不明白。這個想法並不是在所有子分支中複製'section-home'部分。這就是爲什麼你需要使用'&'。 – dfsq

+0

準確地做到了這一點,就像在你的例子中那樣;但是我不能用這種方法來使用'&'。 –

+0

@AndrévanToly你可以,只是不使用根標籤選擇器。 – dfsq