将颜色定义转换为在SASS中设置背景颜色的类

时间:2014-05-27 19:32:11

标签: css sass

假设我有一个像这样的模块按钮(button.scss):

.m-button {
    width: 125px;
    height: 35px;
    color: white;
    display: inline-block;
}

这样的颜色文件定义了颜色(colors.scss):

$light-grey: #EFEFEF;
$dark-grey: #4E4E4E;
$less-dark-grey: #5F5F5F;

我希望能够在我的网站中放置这些按钮,并通过为其分配正确的类来轻松选择按钮的背景颜色:

<div class="m-button background-light-grey">Click Me </div>

但我想避免编写所有背景颜色定义。是否可以在SASS中使用mixins或函数来基本查看我的所有颜色并为每个颜色制作背景颜色类,以适当地设置背景颜色样式?

1 个答案:

答案 0 :(得分:1)

检查以下解决方案:

$colors: (
  light-grey: #EFEFEF,
  dark-grey: #4E4E4E,
  less-dark-grey: #5F5F5F
);

@mixin button-colors {
  @each $name, $color in $colors {
    .background-#{$name} {
      background: $color;  
    }
  }
}

@include button-colors;

.m-button {
  width: 125px;
  height: 35px;
  color: white;
  display: inline-block;
}

输出

.background-light-grey {
  background: #efefef;
}

.background-dark-grey {
  background: #4e4e4e;
}

.background-less-dark-grey {
  background: #5f5f5f;
}

.m-button {
  width: 125px;
  height: 35px;
  color: white;
  display: inline-block;
}

示例:http://sassmeister.com/gist/2f6822da159348908041