These are the basics of CSS custom properties and how to apply opacity to a background color using them.
Create a custom property for color
Let’s create a custom property for a background color. In your CSS file, declaring a custom property looks like this:
:root {
--background-color: #ff7575;
}
Custom property should start with two dashes ‘–’. It’s always a good idea that giving the property a name that clearly shows its purpose.
If you need to use custom properties site-wide, you can declare them at root like this sample, or write them inside of html selector, both are fine.
Then using custom property looks like this:
div {
background-color: var(--background-color);
}
In this sample, color #ff7575 is given to div elements as a background color.
One of the benefits of using custom properties is that it can reduce repetitions in your code. When you need to apply the same background color to multiple elements, it’s much easier to use custom property like above sample than write a color code (#ff7575) many times. And it also makes it easier to maintain the code.
Create a custom property of RGB values
We just created a custom property for a background color, let’s apply it to an element.
.nice-background {
background-color: var(--background-color);
}
Now this page has a beautiful underwater photo as a background, let’s make this nice div transparent. What do we do when we want to apply opacity to an element? An opacity parameter can be used like this:
opacity: 0.5;
Give opacity to this nice div and let’s take a look at it:
We can see the background image through this div, but the text “Nice DIV” also became transparent. This is not cool and a little hard to read that text. How are we able to make only the background color transparent?
There is a way to solve this. Let’s create another custom property.
--background-color-rgb: 255, 117, 117;
This new custom property has RGB values of the same color (#ff7575), like rgb(255, 177, 117). We can use this format to add opacity to color. Don’t include the word “rgb” and round bracket in a custom property.
.awesome-background {
background-color: rgba(var(--background-color-rgb), 0.5);
}
Here’s a sample:
Using RGB values makes only background color transparent, and we can read “Awesome DIV” text clearly.
In Closing
When you use a custom property of color and you want to apply opacity to it on some elements, it will come in handy to create another custom property consists of RGB values of the same color.
That’s all for today.
See you
Photo credit: Jeremy Bishop on Unsplash