CSS variables question (specifically for setting a colour)

Hi all, I haven’t done a blog in nearly a decade so when I got Ghost up and going I was reaching deep into the recesses of my brain for my self-taught CSS and js skills.

In the theme stylesheets I noticed a bunch of things are using variables like var(–ghost-accent-color) which I never knew CSS could do — unless that’s an addition past when I stopped maintaining my own site. Anyway, my problem is that I would like to use the ghost-accent-color variable for a header banner but slightly tweak the opacity. I know I can do this with background-color: rgba (etc) but if I’m setting the colour to a variable it doesn’t seem possible to do this. Similarly, I can add opacity but that will affect the entire header (nav links, subscribe button, etc) and not simply the background colour.

So is there a way to use a variable to set the colour but then tweak the transparency of it in some way? My accent colour is an accent for a reason, but as a banner it’s too intense. I’m trying to see if there’s an option to avoid hard-coding it in the CSS or not.

Thank you!

1 Like

Depending on your target demographic (do they use modern browsers?), you can use the newish relative color syntax:

<style>
.selector {
  background-color: color(from var(--ghost-accent-color) srgb r g b / 0.5)
}
</style>

In this example, the color is converted from the --ghost-accent-color variable to srgb (which is kind-of the default value for most browsers), then the initial r/g/b values are used, but a new alpha value is used.

You can do fun things like shift (g b r), or intensify (calc(r * 1.5) g b) as well

1 Like

You can use color-mix as well. Check this article: una.im | Using color-mix() to create opacity variants

Thanks both, that was a lot of help.

@vikaspotluri123 this was perfect and did exactly what I was after and was a bit easier for me to get my head around than the color-mix syntax. Thank you tons!

4 Likes