Change CSS RGBA color based on main template color in SASS

时间:2018-07-25 04:47:18

标签: sass scss-mixins

I am writing HTML template with SASS.

What I want to achieve is whenever my client change the main template color, the box-shadow color will also be changed and match with the template color.


I have a main template color variable and box shadow mixin.

$template-color: #6c8ce2;

Box shadow color

@mixin box-shadow($amount,$blur,$spread,$opacity) {
  box-shadow: $amount $blur $spread rgba(49, 2, 190, $opacity);
  -webkit-box-shadow: $amount $blur $spread rgba(49, 2, 190, $opacity);
  -moz-box-shadow: $amount $blur $spread rgba(49, 2, 190, $opacity);
}

Here, as rgba color code is different with the main template color.This will not work. So I try to achieve it with two options as below.


Method One
I try to replace rgba color with $template-color something like this

box-shadow: $amount $blur $spread $template-color;

But the problem is the box shadow's opacity need to be very soft and transparent.

Example box shadow image is here

I can't achieve it without using RGBA's opacity.


Method two
I also try adding an alpha hex behind $template-color like this.

box-shadow: $amount $blur $spread $template-color+2b

The method two problem is every color has its' own alpha hex. It's dynamic and I can't guess it.

Can I achieve it without using javascript?

1 个答案:

答案 0 :(得分:0)

Change your mixin like this to genarate the RGBA from your $template-color:

@mixin box-shadow($amount, $blur, $spread, $opacity, $template-color) {
  $red: red($template-color);
  $blue: blue($template-color);
  $green: green($template-color);
  box-shadow: $amount $blur $spread rgba($red, $green, $blue, $opacity);
  -webkit-box-shadow: $amount $blur $spread rgba($red, $green, $blue, $opacity);
  -moz-box-shadow: $amount $blur $spread rgba($red, $green, $blue, $opacity);
}

Update:

I have found that the rgba function accepts two patameters (color and opacity) and you can do this simpler:

@mixin box-shadow($amount, $blur, $spread, $opacity, $template-color) 
{
  box-shadow: $amount $blur $spread rgba($template-color, $opacity);
  -webkit-box-shadow: $amount $blur $spread rgba($template-color, $opacity);
  -moz-box-shadow: $amount $blur $spread rgba($template-color, $opacity);
}