2015-10-08 57 views
4

我想定義就像SCSS mixin,如何連接單元? (PX,%,EM)

.bg-1 { 
    width: 1% 
} 
.bg-2 { 
    width: 2% 
} 

類和我想這一點:

@for $i from 1 through 100 {  
    .bg-#{$i} { 
    width: #{$i}; 
    } 
} 

這至少編譯,但打印出

.bg-1 { 
     width: 1; 
    } 
    .bg-2 { 
     width: 2; 
    } 

問題是如果我加:

width: #{$i}%; 

我:

error sass/screen.scss (Line 294 of sass/modules/_classes.scss: Invalid CSS after " $var: ": expected expression (e.g. 1px, bold), was "%;") 
+0

嘗試'寬度:#{$ I} + '%';'或'寬度:#{$ I} '%';' –

+0

這產生'.bg-95 {寬度:95 +「% 「}'或'.bg-95 {width:95」%「}'... –

+0

@cimmanom如果你的意思是我應該''percent:1%'然後'width:#{$ i} * $ percent ;'我之前試過...並且結果是'.bg-95 {width:95 * 1%「}' –

回答

1

嘗試這種解決方案。有用。

@for $i from 1 through 100 {  
    .bg-#{$i} { 
    $percentage: unquote("%"); 
    width: #{$i}$percentage; 
    } 
} 

或者這樣:

@for $i from 1 through 100 {  
    .bg-#{$i} { 
    width: #{$i}unquote("%"); 
    } 
} 
+0

絕對不是,這是100%錯誤的錯誤,不要這樣做 – cimmanon

+0

你能告訴我爲什麼這是錯誤的? – marisaroque

+0

是的,爲什麼?。你不能只說和不詳細說明。 –

0

或者這樣的事情,這是比較流行的。

@for $i from 1 through 100 {  
    .bg-#{$i} { 
    width: round(percentage($i/100)); // Math function 
    height: #{$i}px; // For px or em just concat 
    } 
} 
+0

絕對不是,這是錯誤的100%錯誤,不要這樣做。 – cimmanon

+0

你在說什麼!?它建立得很好,不是黑客,這不是一個問題,而是一些實際可行的事情它被完成與否。 Sass不會拋出錯誤,所以這是一個正確的答案。 – sperovic

+0

僅僅因爲它編譯不會使它成爲「正確的」答案。 – cimmanon