This article is dedicated to an overview of my Sass work that makes life easier when working with colors in layout. We will look at 3 approaches that will bring together comfort in working with flowers.
As a result, such an entry:
body{
color: color(primary);
background: color(primary, 0.5);
}
Equivalent to this:
:root {
--color-pink: #E20071;
--color-pink--rgb: 226, 0, 113;
}
body {
color: var(--color-pink);
background: rgba(var(--color-pink--rgb), 0.5);
}
But, at the same time, you use only the HEX color format in the control. Conversion takes place automatically. No dancing with a tambourine. We look:
Automatic creation of CSS variables
, .
$colors : (
"pink" : #E20071,
"blue" : #00A3DA,
"gray" : #939394,
"white" : #FFFFFF,
"black" : #1B1B1B,
);
, CSS , $colors :root.
:root{
@each $key, $value in $colors {
--color-#{$key} : #{$value};
}
}
, :
:root {
--color-pink: #E20071;
--color-blue: #00A3DA;
--color-gray: #939394;
--color-white: #FFFFFF;
--color-black: #1B1B1B;
}
Sass RGB , HEX. , :
@function HexToRGB($hex) {
@return red($hex), green($hex), blue($hex);
}
,
:root {
--color-pink-rgb: #{HexToRGB(#E20071)};
}
rgba, — , — . 0 ( ) 1 ( ):
body{
background: rgba(var(--color-pink-rgb), 0.5);
}
CSS
CSS , color.
@function color($name) {
@return var(--color-#{unquote($name)});
}
:
body{
background: color(pink);
}
:
body{
background: var(--color-pink);
}
, 3 , (CSS ) , :
body{
color: color(primary);
background: color(primary, 0.5);
}
:
$colors_theme : (
"primary" : "pink",
"secondary" : "blue"
);
$colors : (
"pink" : #E20071,
"blue" : #00A3DA,
"gray" : #939394,
"white" : #FFFFFF,
"black" : #1B1B1B,
);
@function HexToRGB($hex) {
@return red($hex), green($hex), blue($hex);
}
@function color($name, $opacity: false) {
@if $opacity {
@return rgba(var(--color-#{unquote($name)}--rgb), $opacity);
} @else {
@return var(--color-#{unquote($name)});
}
}
:root{
@if $colors {
@if $colors_theme {
@each $key, $value in $colors_theme {
--color-#{$key} : var(--color-#{$value});
--color-#{$key}--rgb : var(--color-#{$value}--rgb);
}
}
@each $key, $value in $colors {
--color-#{$key} : #{$value};
--color-#{$key}--rgb : #{HexToRGB($value)};
}
}
}
, , .
Moreover, using these functions, having as an input color only in the HEX format, you can easily change the color palette of the site. And do not resort to additional code movements .
I ask you not to judge strictly - this is the first article on Habré.