首页 文章

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

提问于
浏览
3

这个问题在这里已有答案:

假设我有一个像这样的模块按钮(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 回答

  • 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;
    }
    

    OUTPUT

    .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

相关问题