2014-05-07 68 views
2

使用不同的變量我有不同的行星薩斯 - 在@each

$mercury-width: 20px; 

$venus-width: 30px; 

$earth-width: 20px; 

和他們的名字的寬度:

` 
$planets: mercury, venus, earth; 
@each $planet in $planets { 
     .#{$planet} { 
     width: #{$planet}-width; 
     } 
    } 

這是行不通的。

預期的結果:

.mercury { 
    width: 20px; 
} 

我可怎麼辦呢?

回答

2

如何:

$planets-width: (mercury: 20px, venus: 30px, earth: 20px); 
@each $name, $width in $planets-width { 
     .#{$name} { 
     width: $width; 
     } 
} 

結果:

/* line 3, ../scss/test.scss */ 
.mercury { 
    width: 20px; 
} 

/* line 3, ../scss/test.scss */ 
.venus { 
    width: 30px; 
} 

/* line 3, ../scss/test.scss */ 
.earth { 
    width: 20px; 
} 

如果你想同時顏色和大小,你可以使用嵌套地圖:

$planets-map: (mercury: (width : 20px, color: red), venus: (width : 30px, color : purple), earth:(width: 20px, color: blue)); 
@each $name, $properties in $planets-map { 
     .#{$name} { 
     width: map-get($properties, width); 
     color: map-get($properties, color); 
     } 
} 

結果:

/* line 3, ../scss/test.scss */ 
.mercury { 
    width: 20px; 
    color: red; 
} 

/* line 3, ../scss/test.scss */ 
.venus { 
    width: 30px; 
    color: purple; 
} 

/* line 3, ../scss/test.scss */ 
.earth { 
    width: 20px; 
    color: blue; 
} 
+0

謝謝你,但是如果我有行星的顏色的循環,我應該讓另一個數組,例如$行星色:(汞:紅色,大地:藍色);之後又有@each。這是太 – JangBi

+0

@JangBi更新 – JAre

+0

非常感謝你:) – JangBi