将两个SCSS背景@mixin合并到一个样式规则中

时间:2017-07-19 03:50:21

标签: css css3 function sass mixins

我有两个SCSS @mixins,我想在一起调用时将它们组合成一个CSS后台规则:

@mixin linear-gradient($color-stop-1, $color-stop-2) {
    background: linear-gradient($color-stop-1, $color-stop-2);
}

@mixin bg-img($img, $bg-repeat: no-repeat, $bg-pos: 0 0, $bg-color: transparent) {
    background: url('#{$path--rel}/#{$img}') $bg-repeat $bg-pos $bg-color;
}

我可以将它们组合成一个长@mixin,但它们都将在项目中单独重用。

我希望制作这个CSS:

background: linear-gradient(#009fe1, #3acec2), url(../img/bg.jpg) no-repeat center bottom transparent;

enter image description here

目前我正在调用两个@mixins:

@include linear-gradient($cerulean, $turquoise);
@include bg-img('bg.jpg', no-repeat, center bottom);

生成输出CSS(如预期):

background: linear-gradient(#009fe1, #3acec2);
background: url(../img/bg.jpg) no-repeat center bottom transparent;

enter image description here

是否可以使用函数将两个@mixins或任何其他简单方法组合起来加入?

1 个答案:

答案 0 :(得分:1)

为什么不创建1个背景mixin,根据您提供的输入可以输出所有3个场景?

https://codepen.io/esr360/pen/LLKKvR?editors=1102

$path--rel: '..';

@mixin background($custom: ()) {

  $options: map-merge((
    'gradient': null,
    'image': null,
    'bg-repeat': no-repeat,
    'bg-position': 0 0,
    'bg-color': transparent
  ), $custom);

  // we have passed both gradient and image
  @if map-get($options, 'gradient') and map-get($options, 'image') {
    background: 
      linear-gradient(map-get($options, 'gradient')), 
      url('#{$path--rel}/#{map-get($options, 'image')}') 
      map-get($options, 'bg-repeat')  
      map-get($options, 'bg-position') 
      map-get($options, 'bg-color');
  }

  // we have passed just gradient
  @else if map-get($options, 'gradient') {
    background: linear-gradient(map-get($options, 'gradient'));
  }

  // we have passed just image
  @else if map-get($options, 'image') {
      background: 
        url('#{$path--rel}/#{map-get($options, 'image')}') 
        map-get($options, 'bg-repeat')  
        map-get($options, 'bg-position') 
        map-get($options, 'bg-color');
  }
}


// USAGE


// Gradient
.foo {
  @include background((
    'gradient': (#009fe1, #3acec2)
  ));
  // OUTPUT: background: linear-gradient(#009fe1, #3acec2);
}

// Image
.bar {
  @include background((
    'image': 'bg.jpg'
  ));
  // OUTPUT: background: url("../bg.jpg") no-repeat 0 0 transparent;
}

// Both
.fizz {
  @include background((
    'gradient': (#009fe1, #3acec2),
    'image': 'bg.jpg',
    'bg-position': center bottom
  ));
  // OUTPUT: background: linear-gradient(#009fe1, #3acec2), url("../bg.jpg") no-repeat center bottom transparent;
}