Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CSS variables with rgba for gradient transparency

Tags:

Is there a way to use CSS variables when specifying gradient colors with transparency, e.g.

:root {
  --accent-color: #dfd0a5;
}

h1{
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(red(var(--accent-color)), green(var(--accent-color)), blue(var(--accent-color)), 1));
}
like image 966
Manish Avatar asked Apr 12 '15 16:04

Manish


People also ask

How do you add transparency to a gradient in CSS?

To add transparency, we use the rgba() function to define the color stops. The last parameter in the rgba() function can be a value from 0 to 1, and it defines the transparency of the color: 0 indicates full transparency, 1 indicates full color (no transparency).

Can you do gradients in CSS?

CSS defines three types of gradients: Linear Gradients (goes down/up/left/right/diagonally) Radial Gradients (defined by their center) Conic Gradients (rotated around a center point)

How you define the function in CSS image for a linear gradient?

The linear-gradient() function is an inbuilt function in CSS which is used to set the linear gradient as the background image. Syntax: background-image: linear-gradient( direction, color1, color2, ... )


1 Answers

You can use variables, but you can't sample the individual red, green and blue components from a single hex value in CSS.

If you're simply looking to apply an alpha component to an existing RGB triplet, you can specify the entire triplet as a comma-separated list of decimal values instead of a hex value, and substitute it directly into the rgba() function as a single opaque token:

:root {
  --accent-color: 223, 208, 165;
}

h1 {
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(var(--accent-color), 1));
}

If you want to specify and control individual R, G and B values with rgba(), you will need to specify a variable for each color component as a decimal value, and reference each variable within the rgba() function like so:

:root {
  --accent-red: 223;
  --accent-green: 208;
  --accent-blue: 165;
}

h1 {
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(var(--accent-red), var(--accent-green), var(--accent-blue), 1));
}
like image 54
BoltClock Avatar answered Sep 25 '22 07:09

BoltClock