Do you ever struggle with creating a consistent color palette for your website? If so, I've got a great solution for you: using variables to create shades of colors in CSS!
Last week you got a good intruction to variables and saw how to create dynamic grid layouts with CSS variables. Today let’s see how they can be used for creating some shades.
Color is one of the most powerful tools at your disposal when designing a website or application. With CSS variables, you can create a color palette that is easy to manage and update. This is very useful when you want different shades of the same color, for a button for instance.
Let's take a look at how easily we can have three different shades of a button.
In the HTML file, we will create a simple button element:
<button class="button">Click me</button>
In CSS, we define three CSS variables --hue
, --saturation
, and --lightness
with default values. Then, we use these variables to set the background color of the button using the hsl()
function.
:root {
--hue: 190;
--saturation: 90%;
--lightness: 40%;
}
.button {
background-color: hsl(var(--hue), var(--saturation), var(--lightness));
color: #fff;
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
}
We can then create lighter and darker shades like so.
/* Set lighter shade */
.button.lighter {
--lightness: 65%;
}
/* Set darker shade */
.button.darker {
--lightness: 32%;
}
To create a lighter shade, we simply set the --lightness
variable to a higher value (in this case, 65%
). To create a darker shade, we set the --lightness
variable to a lower value (in this case, 32%
).
You can adjust the lightness
parameter to create a wide range of shades. A lightness value of 90% creates a very light shade, while a value of 20% creates a darker shade. You can experiment with different values to find the perfect shades for your design.
Here’s the full demo of the same on CodePen
And that's it! With just a few lines of code, you can create a color palette that is easy to manage and update.
That is a great idea. Not tested, but what about extending it to
:root {
--hue: 190;
--saturation: 90%;
--lightness: 40%;
--alpha: 100%;
}
.button {
background-color: hsl(var(--hue) var(--saturation) var(--lightness) / var(--alpha));
}