Defining color palette in SASS with variables

Sass is probably the de facto for styling web applications today. I think many designers prefer Sass for its simple and powerful variables along with some other cool features. With variables, defining color schemes for your awesome web design is as easy as pie. It helps in re-using colors through out the project resulting in maintainable and clean code.

We can simply define color variables as below:

$blue           : #22678C;
$lightBlue : #23778G;
$lighterBlue : #48525C;
$yellow : #ffa949;
$lightYellow: : #eda2fs;

Some designers create maps for color variables which can be accessed using simple map-get

$palette: (
blue : #22678C,
lightBlue : #23778G,
lighterBlue : #48525C,
yellow : #ffa949,
lightYellow: : #eda2fs
background-color: map-get($palette,blue);

We can make this code a little better by grouping similar variables using JSON like structure.

$palette: (
blue: (
base: #23778G,
light: #23778G,
lighter: #48525C
yellow: (
base: #ffa949,
light: #eda2fs
background-color: map-get(map-get($palette, blue), base);

While this nested map-get
gets job done, but the code looks a little messy. We can create our own little function.

@function color($color,$tone){

@warn map-get($palettes,$color);

@if map-has-key($palettes,$color){
$color: map-get($palettes,$color);

@if map-has-key($color,$tone){
$tone: map-get($color,$tone);
@return $tone;

@warn "unknown tone `#{$tone}` in color";
@return null;

@warn "unknown color `#{$color}` in palette";
@return null;


Now, we are able to access the color values simply as below:

background-color: color(blue,base);

This now looks so nice. I wonder why it is not in SASS by default.

Simplify color variations with HSL

In our sass projects, we have to work with different color shades and variables. Defining color shades with hex (or rgb) as above just does not feel intuitive. So, we can use HSL for simpler color variables. Once you get hang of hsl, it is kind of difficult to get back to hex and rgb values.

hsl(201, 61%, 34%)

This makes generating color palette for our project a lot simpler.

$palettes: (
blue: (
darker: hsl(201, 61%, 34%),
dark: hsl(198, 57%, 39%),
base: hsl(196, 59%, 42%),
light: hsl(194, 56%, 51%),
lighter: hsl(192, 61%, 53%),

red: (
base: hsl(0, 100%, 58%)

This approach has helped me generate better color palettes and write DRY code in my projects. If you like this approach or have any feedback, do let me know. :)

稿源:YoungInnovations’ Blog (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Defining color palette in SASS with variables

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录