Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LESS Mixin/Function to change a @Color HEX to RGBA to PASS into another mixin

Tags:

less

I want to convert a base color in HEX (@color) to rgba and use that in a mixin like .box-shadow(x y b color);

I have seen a load of mixins to convert HEX to RGBA and set background-color, and I know I can create my own mixing for box-shadow. But is there a generic solution so we can use any existing mixin.

Tried/want something like this (doesn't work) :

/** Extend LESS functions like (lighten, darken, mix) **/
rgbaColorIn(@color, @opacity : 1){
  return rgba( red(@color), green(@color), blue(@color), @opacity );
}

// ----- or ------

/** Passing in a reference to mixin and params **/
.rgbaColorIn(@selector, @params, @color, @opacity : 1){
  @rgbaColor: rgba( red(@color), green(@color), blue(@color), @opacity );
  @selector(@params @color);
}
like image 584
Labithiotis Avatar asked Nov 27 '22 01:11

Labithiotis


2 Answers

There is no return keyword in less. If you want a mixin that returns a value, then you can define a variable inside it, for example:

.rgbaColorIn(@color, @opacity : 1){
  @result: rgba( red(@color), green(@color), blue(@color), @opacity );
}

which you can access in the scope you call the mixin:

.section {
  .rgbaColorIn(red, 50%);
  background-color: @result;
}

But if you just want to generate a RGBA from a RGB color, you can use the fade function:

.section {
  @result: fade(red, 50%);
  background-color: @result;
}

which will render the same result in CSS:

.section {
  background-color: rgba(255, 0, 0, 0.5);
}

A .box-shadow mixin to pass the RGB color and opacity/alpha separately could be something like this:

.box-shadow(@x; @y; @b; @color; @opacity) {
   box-shadow: @x @y @b fade(@color, @opacity);
   -moz-box-shadow: @x @y @b fade(@color, @opacity);
   -webkit-box-shadow: @x @y @b fade(@color, @opacity);
}

Which you could use in a selector like this:

.section {
  .box-shadow(2px; 2px; 1px; pink; 50%);
}

and obtain this CSS:

.section {
  box-shadow: 2px 2px 1px rgba(255, 192, 203, 0.5);
  -moz-box-shadow: 2px 2px 1px rgba(255, 192, 203, 0.5);
  -webkit-box-shadow: 2px 2px 1px rgba(255, 192, 203, 0.5);
}
like image 70
helderdarocha Avatar answered Dec 20 '22 10:12

helderdarocha


To get an rgba value (assuming you are giving it something other than 100% opacity, since LESS will just keep it as a hex value in that case), just use the fade() function. So...

LESS

@color: #ff0000;

.test {
  box-shadow: 2px 2px 5px fade(@color, 99%); 
}

CSS Output

.test {
  box-shadow: 2px 2px 5px rgba(255, 0, 0, 0.99);
}
like image 43
ScottS Avatar answered Dec 20 '22 11:12

ScottS