2016-08-25 43 views
2

使用諸如Modernizr之類的庫,您可以在html標記中獲得一些具有不同瀏覽器功能的類,例如,如果無法執行css轉換html標記,則會獲取no-csstransforms類。 什麼我想要做的是寫一個元素的CSS屬性和分裂他們基於一個html類,例如:LESS/CSS從元素聲明中選擇父項

.my-element { 

[SomethingThatCanSelectAparent]html.csstransforms & { 
     // i can do transforms to this element 
} 
[SomethingThatCanSelectAparent]html.no-csstransforms & { 
    /// whatever you want do for older browsers 
} 

} 

我知道,我可以從html.whaterver { .my-element }開始,但在大型網站會很煩人

我怎樣才能以這樣的乾淨方式實現它?

回答

3

你是對的,但你的方法有點奇怪。

這主要是因爲CSS沒有parent選擇器,比如<之類的東西。所以你必須給經典倒下(如CSS是彪是),這意味着:

// Declaring the top of the DOM first 
html.css-transforms { 
    // Specific element when DOM has class x 
    .my-element { 
     // transformations! 
    } 
} 

// And when the HTML has no such thing, 
html.no-css-transforms { 
    // Give this styling. 
    my-element { 
     // no transformations :(
    } 
} 

這將基於該html標籤的類風格my-element

然而,有可能utilizing the ampersand (&) with LESS.

.my-element { 

    html.css-transforms & { 
     // Magic css transforming 
    } 
} 
+0

哦,那還沒有,當我發佈這個,哎。這仍然是他的問題的答案,在傳統的CSS中是不可能的。 – Roberrrt

4

在SASS和LESS,你應該能夠像這樣的符號來實現:

.your-element { 

    color: red; 

    html.csstransforms & { color: blue; } 

} 

和這應該是輸出:

.your-element { color: red; } 
html.csstransforms .your-element { color: blue; } 

編輯:

對不起,一開始讀錯了問題,給了SASS答案,但是同樣應該在LESS中工作。

+1

LESS對&符有相同的語法選項,請參閱http://blog.slaks.net/2013-09-29/less-css-secrets-of-the-ampersand/ – Roberrrt

+0

糟糕,不知何故,我讀了「LESS/SASS從元素聲明中選擇父項「。對不起,看看LESS是否有類似的東西。 – thepio

+1

謝謝@Roberrrt。所以同樣也應該在LESS中工作。 – thepio