In an earlier post, we looked at Named Colors in CSS. Currently there are 147 named CSS colors that you can use, ranging from primary colors like red
, green
, and blue
, to more exotic choices like tomato
, aquamarine
, and mediumslateblue
. But what if you want to have your own named CSS colors? Is that possible?
The answer is both yes and no. First, the bad news. If you’re working with just CSS and not a preprocessor like SASS or LESS , the code will not look as clean as the native custom colors. On the pluse side, the way to add custom colors is to use CSS variables . This approach is not as clean as if you were using something like SASS but that’s out of the scope of this article. Let’s see how it works.
Creating Custom CSS Colors with CSS Variables
To add a new named color to CSS for your application, we’ll need to utilize CSS custom properties and the :root
pseudo-element. Let’s say we wanted to create a new color called adoblue
. We would add a custom variable to the :root
pseudo-element and define our variable as such:
:root {
--adoblue: #1a202c;
}
Notice the two dashes (--
) before the variable name. This is required per the CSS custom properties spec. Once we have the custom variable defined, we can use it anywhere in our application like so:
body {
background: var(--adoblue);
}
To access our custom CSS variable, we use the var()
method. Variable names are case sensitive, so --adoblue
is different from --AdoBlue
. Additionally, CSS custom properties conform to the cascading nature of CSS. So, if in the :root
pseudo-element, which affects the entire page, you define a custom variable, and redeclare a variable further down in your page, the variable will be overwritten. To see an example of this, let’s assume we have this piece of CSS code:
:root {
--adoblue: #1a202c;
}
body {
--adoblue: #000000;
background: var(--adoblue);
}
In this instance, our body
background would be #000000
or black instead of the dark blue from our :root
element. Typically, you’d want to declare all your variables at the root level to avoid this.
Summary
Defining custom color names in CSS is possible through the use of CSS variables. The caveats to custom CSS colors is that the custom color names will start with two dashes, for example --adoblue
, and to utilize these custom values, we’ll need to make use of the var()
CSS function. CSS variables can be used for much more than just custom color names.
Happy hacking.