您当前的位置:首页 > 计算机 > 编程开发 > Html+Div+Css(前端)

使用 Sass 编写 CSS Blend Modes

时间:12-14来源:作者:点击数:
CDSY,CDSY.XYZ

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

看看最后的效果:

CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐