LESScss converting rgba to hex? how to nest color variables into a mixin?

北城以北 提交于 2019-12-02 16:46:28

Turns out, less has hsla functions built in (see less color functions). So with some help, here's what we discovered:

    @dkblue: #11374c;
    .colorize_bg(@color: @white, @alpha: 1) {
           background: hsla(hue(@color), saturation(@color), lightness(@color), @alpha);}

Then use the mixin:

section {.colorize_bg(@dkblue,1);}

So we pass in the color variable @dkblue and less' functions like hue(@color) take @dkblue and pull out its hue, saturation, and lightness values. We can then pass in an alpha that we define in that mixin.

Then I can use it in other ways, like to define transparent borders. By adding background-clip: padding-box; to .colorize_bg I ensure that my borders show outside of the bg box color (isn't CSS3 magical?) Then I can redefine the mixin to work for border color:

    .colorize_border(@color: @white, @alpha: 1) {border-color: hsla(hue(@color), saturation(@color), lightness(@color), @alpha);}

and then give section the border width, style, and define color via the mixin:

section {border-width: 0 10px; border-style: solid; .colorize_border(@dkblue, .5);

And you'll get magical, shiny transparent borders, like so: http://i.stack.imgur.com/4jSKR.png

Ryan Wheale

LESS has a set of functions to fade, fadeIn, or fadeOut a color. You should be able to pass any color to these mixins (hsl, rgb, rgba, hex, etc.)

// fade color to 40%
color: fade(#000000, 40);

// fade in color by 10%
color: fadeIn(rgba(0, 0, 0, .5), 10);

// fade out color by 10%
color: fadeOut(rgba(0, 0, 0, .5), 10);

You don't need to convert to hsla either so you won't need a white value

.hexBackgroundToRGBA(@color,@alpha){
  @myred:red(@color);
  @mygreen:green(@color);
  @myblue:blue(@color);
  background-color: @color;
  background-color: rgba(@myred,@mygreen,@myblue,@alpha);
}

You'll have to write a few of these mixins in you need to set stuff other than the background-color property set but that's the idea. Just call it like this:

#selector{  .hexBackgroundToRGBA(@gray, 0.8); }

That will take whatever color val you have in the @gray variable and output a cross browser solution at 80% transparency with a solid color fallback for browsers that don't support rgba().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!