To apply transparency to an element, you can use opacity in CSS. However, sometimes you don't want to make the entire element transparent, only a color.
Using not-so-modern CSS, you can simply generate non-opaque versions of a color without any preprocessor like Sass. This card describes how to do that.
Note that we're not talking about defining colors with transparency. This is about the case where you have a color but need a more transparent variant of it (e.g. for a border, background, etc.), and where your component does that without defining the transparent variant up front.
How to generate a transparent color variant
There are two ways to do this easily with just CSS:
- Using the
color-mixfunction - Relative Color Syntax with color functions like
rgborhsl
color-mix
The color-mix function allows mixing two colors, and one of the colors can just be transparent:
--color: #f00
--transparent-color: color-mix(in srgb, var(--color), transparent 75%)
Note that we're mixing in the sRGB color space. This should be perfectly fine for transparency, but any other color space (like in hsl) should be fine as well.
Relative Color Syntax
CSS veterans may remember the rgb to work like rgb(0, 255, 0) -- its modern variant does not use commas and can define transparency as well, like rgb(0 255 0 / 50%).
With Relative Color Syntax, you can adjust the transparency of any color.
--color: #f00
--transparent-color: rgb(from var(--color) r g b / 25%)
This just defines a new RGBA color from the given color, with 25% opacity (to achieve 75% transparency).
Obviously, hsl(from var(--color) h s l / 25%) or similar would also work.
Example usage
Use this to make any color referenced through a Custom Property, or the current text color (currentColor) transparent.
Both approaches described here work. Just choose the one that is more readable for you.
.demo {
--transparent-color: color-mix(in srgb, currentColor, transparent 75%);
background: var(--transparent-color);
}
Codepen demo: https://codepen.io/foobear/pen/raaLggr Show archive.org snapshot
Browser support
color-mix
The color-mix function has been available since early 2024.
- Chrome/Edge 111+
- Firefox 113+
- Safari 16.2+
https://caniuse.com/wf-color-mix Show archive.org snapshot
Relative Color Syntax
This worked for a while with small caveats. Full browser support landed end of 2024.
- Chrome/Edge 131+
- Firefox 133+
- Safari 18.0+
https://caniuse.com/css-relative-colors Show archive.org snapshot