2015-05-09 77 views
1
開頭

我正在循環訪問sass中的一個名稱列表,並且當它到達類名以數字開頭的點時,sass似乎正在中斷。事實上,當我註釋到以數值開頭的類名時,sass編譯運行良好。這就是說我不能重命名類名。我如何才能使它工作?下面的代碼是我嘗試:Sass循環遍歷類名稱,以

@each $car in 
    bmwwhite 
    hondared 
    //22ltr-porche 
    //30ltr-cossworth 
{ 
    .#{$car} { 
    background:url(/img/cars/#{$car}.jpg) no-repeat 
    } 
} 

回答

1

HTML5是細跟開始的ID和類名帶數字的這些天,但CSS不是(Here's some info about all this)。

Sass可能不會允許您創建無效的CSS選擇器,如.22ltr-porche,這樣纔有意義。雖然有辦法解決它。

你可以試試這個:

@each $car in 
    bmwwhite 
    hondared 
    22ltr-porche 
    30ltr-cossworth 
{ 
    [class="#{$car}"] { 
    background:url(/img/cars/#{$car}.jpg) no-repeat 
    } 
} 

這將創建一個選擇,看起來像這樣[class="22ltr-porche"]Sass is OK with that.

不合格的屬性選擇這樣往往很慢,但。你應該嘗試將屬性選擇器與更具體的東西結合起來。這是一個example plunkr

+0

該輸出是[class =「bmwwhite」] { background: 因此輸出在.css文件中是錯誤的:/ –

+0

@ReneZammit這不正常嗎? – miphe

+0

不,它不是因爲輸出應該是.bmwwhite {background:............} 而是輸出是這樣來的[class =「bmwwhite」] {background:..... ..} –

1

您嘗試生成的課程無效。通過驗證運行它會給這個錯誤:

In CSS1, a class name could start with a digit (".55ft"), unless it was a dimension (".55in"). In CSS2, such classes are parsed as unknown dimensions (to allow for future additions of new units) To make "22ltr-porche" a valid class, CSS2 requires the first digit to be escaped ".\32 2ltr-porche" [22ltr-porche]

所以,我們需要逃避領先的數字像它說:

@function escape_leading_numbers($s) { 
    $first-char: str_slice(#{$s}, 0, 1); 
    $found: index('1' '2' '3' '4' '5' '6' '7' '8' '9' '0', $first-char); 
    @return if($found, unquote(str-insert(str-slice(#{$s}, 2), "\\3#{$first-char} ", 1)), $s); 
} 

$name: '007'; 

.#{escape_leading_numbers($name)} { 
    color: red; 
} 

@each $car in 
    bmwwhite 
    hondared 
    22ltr-porche 
    30ltr-cossworth 
{ 
    .#{escape_leading_numbers($car)} { 
    background:url(/img/cars/#{$car}.jpg) no-repeat 
    } 
} 

輸出:

.bmwwhite { 
    background: url(/img/cars/bmwwhite.jpg) no-repeat; 
} 

.hondared { 
    background: url(/img/cars/hondared.jpg) no-repeat; 
} 

.\32 2ltr-porche { 
    background: url(/img/cars/22ltr-porche.jpg) no-repeat; 
} 

.\33 0ltr-cossworth { 
    background: url(/img/cars/30ltr-cossworth.jpg) no-repeat; 
} 

http://sassmeister.com/gist/e07d3fd4f67452412ad0