2014-03-26 29 views
1

我在sass中有一種新鮮感,在練習時我遇到了這種情況。使用sass @each或@for控制指令循環餘量補償

如何使用不同的值偏移量(我知道這可能聽起來不清楚)來實現邊緣頂邊,邊距右邊距,邊距底邊和邊距左邊的列表。

因此,這裏是.scss

.offset-top-1{ 
    margin-top: 1rem; 
} 
.offset-top-2{ 
    margin-top: 2rem; 
} 
.offset-top-3{ 
    margin-top: 3rem; 
} 
//.... so on to .offset-top-6 and also for .offset-right-x, .offset-bottom-x, and .offset-left-x 

輸出生成的.css文件中(應該是)這是我的.scss文件

@mixin offset-margin($margins){ 
     margin: $margins; 
    } 

    @for $i from 1 through 20 { 
     .offset-top-#{$i}{ 
      @include offset-margin(1rem * $i 0rem 0rem 0rem); // the other offset values should be removed since I'm dealing only for margin-top 
     } 
     .offset-right-#{$i}{ 
      @include offset-margin(0rem 1rem * $i 0rem 0rem); 
     } 
     .offset-bottom-#{$i}{ 
      @include offset-margin(0rem 0rem 1rem * $i 0rem); 
     } 
     .offset-left-#{$i}{ 
      @include offset-margin(0rem 0rem 0rem 1rem * $i); 
     } 
    } 

編輯:

@mixin指令偏移餘量只允許「餘量」,但我想實現的是有sp ecific緣位置e.g保證金權,保證金左等

+0

什麼毛病SASS你提供的? – fcalderan

+0

@ mixin指令偏移保證金只允許「保證金」,但我想實現的是具有特定的保證金位置,例如保證金 - 右側,保證金 - 左側等。 – Vincent

回答

4

試試這個代碼(在http://sassmeister.com/測試)

@mixin offset-margin($margin, $value){ 
    margin-#{$margin}: $value; 
} 

@for $i from 1 through 20 { 
    @each $margin in top, left, bottom, right { 

    .offset-#{$margin}-#{$i}{ 
     @include offset-margin($margin, 1rem * $i) 
    } 

    } 
} 
+0

完美!謝謝! – Vincent

+0

我剛剛做了一些小改動。 – fcalderan

+0

是的,這個實現比第一個更容易理解。謝謝! – Vincent