【问题标题】:Sass @for loop - from one color to another colorSass @for 循环 - 从一种颜色到另一种颜色
【发布时间】:2015-05-27 15:50:11
【问题描述】:

我需要创建一个 CSS 背景颜色列表,逐渐变暗以达到目标黑暗。我知道可以使用此处所述的技术:Sass: Change color with @for loop 但是我想从一种颜色调制 另一种颜色。不只是让颜色越来越深。

我有可变数量的项目,希望背景颜色从白色变为黑色。基本上是定义了开始和结束颜色的阶梯渐变。

所以如果我有三个项目,我希望输出是这样的:

.class1 {
  background-color: #fff;
}
.class2 {
  background-color: #808080; // 50% brightness
}
.class3 {
  background-color: #000;
}

如果我有五个项目,它看起来像这样:

.class1 {
  background-color: #fff;
}
.class2 {
  background-color: #bfbfbf; // 75% brightness
}
.class3 {
  background-color: #808080; // 50% brightness
}
.class4 {
  background-color: #404040; // 25% brightness
}
.class5 {
  background-color: #000;
}

开始和结束颜色应该始终相同,但中间颜色需要根据循环中的项目总数自动调整。

我不知道用 Sass 是否可以实现这样的事情??

【问题讨论】:

  • 如果您希望背景颜色从白色变为黑色,那么您链接到的示例应该适合您,因为您可以从 #fff 开始,它将使其变暗直到变黑。但是,如果您希望它从红色变为蓝色,我不确定,抱歉。

标签: css for-loop sass


【解决方案1】:

这里你需要的函数是mix();

$color-1: white;
$color-2: black;

$steps: 5;

@for $i from 0 to $steps {
    .class-#{$i + 1} {
        background: mix($color-1, $color-2, percentage($i / ($steps - 1)));
    }
}

输出:

.class-1 {
  background: black;
}

.class-2 {
  background: #3f3f3f;
}

.class-3 {
  background: #7f7f7f;
}

.class-4 {
  background: #bfbfbf;
}

.class-5 {
  background: white;
}

http://sassmeister.com/gist/d0fc452765908aac2617

希望它们以相反的顺序排列?只需交换颜色即可。

【讨论】:

  • 这正是我所需要的!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 2012-02-18
  • 2013-08-15
相关资源
最近更新 更多