使用Sass编写CSS Blend Modes

CSS Blend Modes是CSS的一个新功能,可以将一个层和元素的背景层混合在一些。常见的是将背景图像和背景颜色混合在一起。

在这篇文章中,我们将来体验一上在几个项目中使用Sass编写的一个简单的混合模式的mixin。从而学习如何使用Sass创建混合模式的mixin,并且怎么使用。

使用混合模式

当在一个元素上使用background-blend-mode属性时,它将背景图像和背景颜色根据设置的混合模式混合在一起。

简单的混合模式的mixin设置三个参数:背景图像路径,背景颜色和混合模式:

@mixin blendy($img, $color, $blend) {
  background-image: url('img/#{$img}');
  background-color: $color;
  background-blend-mode: $blend;
}

现在我们可以在需要设置混合模式的地方像这样调用设置好的blendy的mixin:

.blend {
  @include blendy("mountains.jpg", firebrick, multiply);
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-size: cover;
}

编译出来的CSS:

.blend {
  background-image: url("img/mountains.jpg");
  background-color: firebrick;
  background-blend-mode: multiply;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-size: cover;
}

使用渐变呢?

CSS混合模式是非常强大的,他还可以让图像和渐变混合。我们一起来创建一个有趣的混合效果。

首先,我们将为我们的混合模式声明一个渐变的变量:

// Blend mode gradient
$bm-gradient: linear-gradient(aqua, royalblue);

接下来,需要调整一下mixin。因为渐变实际上是background-image而不是background-color,因此在mixin中添加一个@if/@else条件来显示多个背景层。可以像设置$color给渐变设置一个参数$bm-gradient:

@mixin blendy($img, $color, $blend) {
  $img-path: url('#{$img}');
  @if $color == $bm-gradient {
    background: $color, $img-path;
  } @else {
    background-image: $img-path;
    background-color: $color;
  }
  background-blend-mode: $blend;
}

这次使用渐变的变量来替代颜色值:

.blend {
  @include blendy("mountains.jpg", $bm-gradient, multiply);
  ...
}

最后的工作

目前,我们仅限于渐变的混合模式,但我们希望这个mixin更强大,能接受各种变量的值。例如:

// Blend mode gradients
$fancy-grad  : linear-gradient(aqua, royalblue);
$transp-grad : linear-gradient(black, transparent);
$snarky-grad : linear-gradient(firebrick 40%, blue);

要做到这一点,我们除了设置$color参数,还会添加一个新参数$grad,而且还会设置null为默认的可选参数。由于会广泛的使用混合模式(至少对我来说)。所以将混合模式的默认值设置为multiply

@mixin blendy($img, $color: null, $grad: null, $blend: multiply) {
  $img-path: url('img/#{$img}');
  @if $grad {
    background: $grad, $img-path;
  } @else {
    background-image: $img-path;
    background-color: $color;
  }
  background-blend-mode: $blend;
}

现在我们可以简单的指定图像,和想要混合颜色或者渐变:

.blend {
  @include blendy("mountains.jpg", #00bfff);
}
.feat {
  @include blendy("featured.jpg", $grad: $fancy-grad);
}

编译出来的CSS:

.blend {
  background-image: url("img/mountains.jpg");
  background-color: #00bfff;
  background-blend-mode: multiply;
}

.feat {
  background: linear-gradient(aqua, royalblue), url("img/featured.jpg");
  background-blend-mode: multiply;
}

看看最后的效果:

译者:如果你从未了解或者接触CSS混合模式,建议先点击这里了解。

本文根据@Guil Hernandez的《CSS Blend Modes with Sass》所译,整个译文带有我们自己的理解与思想,如果译得不好或有不对之处还请同行朋友指点。如需转载此译文,需注明英文出处:http://sassbreak.com/css-blend-modes-with-sass/

大漠

常用昵称“大漠”,W3CPlus,Sass中国创始人,目前就职于Ctrip UED。中国Drupal社区核心成员之一。对HTML5、CSS3和Sass等前端脚本语言有非常深入的认识和丰富的实践经验,尤其专注对CSS3的研究,是国内最早研究和使用CSS3技术的一批人。CSS3、Sass和Drupal中国布道者。2014年出版《图解CSS3:核心技术与案例实战》。

如需转载,烦请注明出处:http://www.w3cplus.com/preprocessor/css-blend-modes-with-sass.html

返回顶部