How to apply transparency to any color with pure CSS
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. 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
CSS' color-mix
function is all you need.
--color: #f00
--transparent-color: color-mix(in srgb, var(--color), transparent 75%)
You can also use currentColor
.
--transparent-color: color-mix(in srgb, currentColor, 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.
Example usage
.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
- Chrome/Edge 111+
- Firefox 113+
- Safari 16.2+
https://caniuse.com/mdn-css_types_color_color-mix Show archive.org snapshot