2017-07-19 1 views
1

に2 SCSSの背景@mixinを組み合わせる:私は2 SCSSは、私が一緒に呼び出されたときに1つのCSSの背景ルールに結合したいと@mixins持って一つのスタイルルール

@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を生産しているしたい

:(予想通り)

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

出力はCSS生産:

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

enter image description here

現在、私は2 @mixinsを呼び出しています

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

enter image description here

2つの@mixinsを組み合わせたり、他の簡単な結合方法を使用できますか?

+0

は、なぜあなたはすべての3つのシナリオは、あなたがそれを与えるの入力に応じて出力することができ1つの背景ミックスインを作成しませんか? –

+0

@EdmundReedサンプルスニペットはありますか? – Kerry7777

+0

私の投稿回答を参照してください –

答えて

1

入力した入力に応じて3つのシナリオをすべて出力できるバックグラウンドミックスインを1つ作成してみませんか?

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

ありがとう@エドムンド私のために働くリード(素敵なスニペット)。 SassyCSSが別のミックスインを呼び出す機能を持っていた場合は冷静になります。 – Kerry7777

+0

このSass機能が実装されている場合は、https://github.com/sass/sass/issues/871 –

関連する問題