css hex color with opacity code example

Example 1: css opacity background color

background: rgba(255, 255, 255, 0.25);

Example 2: background color with opacity

h1 {background-color:rgba(255,0,0,0.3);}

Example 3: background opacity css hex

background-color: #ff000088; <--- the 88 is the alpha
background-color: #ff0000 50%;

Example 4: javascript add alpha to hex

function addAlpha(color: string, opacity: number): string {
    // coerce values so ti is between 0 and 1.
    const _opacity = Math.round(Math.min(Math.max(opacity || 1, 0), 1) * 255);
    return color + _opacity.toString(16).toUpperCase();
}
addAlpha('FF0000', 1); // returns 'FF0000FF'
addAlpha('FF0000', 0.5); // returns 'FF000080'

Tags:

Css Example