关联数组SCSS / SASS

时间:2014-01-25 00:23:24

标签: arrays sass

我需要将数字转换为单词,所以:

  • “1-3” - > “三分之一”
  • “3-3” - > “三分之三”
  • “2-5” - > “五分之二的”

数字是在一个循环中生成的,它应该输出一堆不同的类名,如one-thirdone-half

$number = 3;

@for $i from 1 through $number-1 {
    // some calculations to output those classes: ".one-third", ".two-thirds"

    // The following currently outputs class names like ".1-3" and ".2-3"
    .#{$i}-#{$number} {
        // CSS styles
    }
}

我想我需要使用两个不同的关联数组,在PHP中(仅作为示例)可能看起来像:

$1 = array( 
   "1"=>"one", 
   "2"=>"two", 
   "3"=>"three" 
);

$2 = array( 
   "1"=>"whole", 
   "2"=>"half", 
   "3"=>"third" 
);

是否可以在 SASS / SCSS 中创建关联数组或是否有解决方法?

2 个答案:

答案 0 :(得分:55)

在Sass< 3.3你可以使用多维列表:

$numbers: (3 "three") (4 "four");

@each $i in $numbers {
    .#{nth($i,2)}-#{nth($i,1)} {
        /* CSS styles */
    }
}

DEMO

在Sass> = 3.3中我们得到地图:

$numbers: ("3": "three", "4": "four");

@each $number, $i in $numbers {
    .#{$i}-#{$number} {
        /* CSS styles */
    }
}

DEMO


所以就分数而言,你可以在这个方向上做点什么,这样你就不需要多个列表或地图了:

$number: 6;
$name: (
    ("one"),
    ("two" "halv" "halves"),
    ("three" "third" "thirds"),
    ("four" "quarter" "quarters"),
    ("five" "fifth" "fifths"),
    ("six" "sixth" "sixsths")
);

然后你想用你的循环做什么......甚至可能是这样的事情= D

@for $i from 1 to $number {
  @for $j from 2 through $number {
    .#{ nth( nth( $name, $i ), 1 ) }-#{
      if( $i>1,
        nth( nth( $name, $j ), 3 ),
        nth( nth( $name, $j ), 2 )
      )} {
        /* CSS styles */
    }
  }
}

DEMO

(我这样编写,以便您可以在@for中注意到,使用to转到n - 1

答案 1 :(得分:1)

除了马丁的回答(我的示例是将颜色用作变量)之外,它还与darken()之类的颜色处理功能一起使用:

$blue: rgb(50, 57, 178);
$green: rgb(209, 229, 100);
$orange: rgb(255, 189, 29);
$purple: rgb(144, 19, 254);

$colors: (
        "blue": $blue,
        "green": $green,
        "orange": $orange,
        "purple": $purple
);

@each $name, $color in $colors {
  .tc-#{$name} { color: #{$color} !important; }
  .bgc-#{$name} { background-color: #{$color} !important; }
}