属于对象的SCSS颜色变量

时间:2016-08-17 09:24:47

标签: variables colors sass naming

我正在重构一个项目的SCSS,将颜色映射到_colors.scss文件中的变量。

通常情况下,我遇到选择器有background-colorcolor的情况。所以,我最终编写了以下变量:

$cool-table-bg: $brand-primary;
$cool-table-text: $white;

很快,我最终得到了上述许多版本。

我想知道的是,我可以像在JavaScript中一样将上述内容分配给对象吗?例如:

$cool-table: {
  bg: $brand-primary;
  text: $white;
}

我希望能够引用$cool-table.bg这样的颜色。

这可能吗?

2 个答案:

答案 0 :(得分:3)

正如Dan Gamble建议的那样,我肯定会选择SASS地图。给自己写一些颜色处理工具。类似的东西:

// define globally somewhere in your setup
$COLORS = ();

// use mixin to define colors groups by e.g. element name
// example: @include color-set(cool-table, bg, #ff0000);
// or pass in a map to define multiple colors at once
// example: @include color-set(cool-table, ( bg: #ff0000, border: #00ff00));
@mixin color-set($group-name, $color-name, $color-value: false) {
  @if (type-of($color-name) == map) {
    @each $name, $value in $color-name {
      @include define-color($group-name, $name, $value);
    }
  }
  @else {
    @if(map-has-key($COLORS, $group-name)) {
      $group: map-get($COLORS, $group-name);
    }
    @else {
      $group: ();
    }
    $group: map-merge($group, ( $color-name: $color-value ));
    $COLORS: map-merge($COLORS, ( $group-name: $group )) !global;
  }
}

// access color values anywhere with this function by passing in 
// element name and color identifier
// example: $bg-color: color-get(cool-table, bg);
@function color-get($group-name, $color-name) {
  @if (map-has-key($COLORS, $group-name)) { 
    $group: map-get($COLORS, $group-name);
    @if (map-has-key($group, $color-name)) {
      @return map-get($group, $color-name);
    }
  }
  @return false;
}

答案 1 :(得分:2)

您可以使用地图。这里写得很好:

https://www.sitepoint.com/using-sass-maps/

要查看可用的功能,您可以转到here并向下滚动到地图功能