Use CSS variables with rgba for gradient transparency

岁酱吖の 提交于 2019-11-27 04:42:16

问题


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));
}

回答1:


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));
}


来源:https://stackoverflow.com/questions/29591465/use-css-variables-with-rgba-for-gradient-transparency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!