我正在尝试使用 CSS 变量,但发生了一些奇怪的事情。我这样声明变量:
:root {
--primary: '#fff';
--black: '#1b1f23';
--gray: '#586069';
--orange: '#f9826c';
--logo: '#fff';
--header: '#24292e';
--search: 'rgba(255; 255; 255; 0.13)';
}
Run Code Online (Sandbox Code Playgroud)
然后我像这样使用它们:
input {
background: var(--search);
}
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,该样式没有被应用。当我将鼠标悬停在 Chrome Devtools 中的变量上时,它会显示正确的值,但它并不适用。
我对如何让它发挥作用非常迷失。
编辑:
我正在使用 React,所以这是渲染<input />
您的代码存在一些问题。变量值不需要是字符串。并且rgba(255; 255; 255; 0.13)应该用逗号分隔,而不是分号。那么就这样了rgba(255, 255, 255, 0.13)。并且这种风格正在被应用;你只是无法注意到差异,因为rgba(255, 255, 255, 0.13)它仍然是白色的。所以正确的 CSS:root是这样的:
:root {
--primary: #fff;
--black: #1b1f23;
--gray: #586069;
--orange: #f9826c;
--logo: #fff;
--header: #24292e;
--search: rgba(255, 255, 255, 1);
}
Run Code Online (Sandbox Code Playgroud)
例子:
:root {
--primary: #fff;
--black: #1b1f23;
--gray: #586069;
--orange: #f9826c;
--logo: #fff;
--header: #24292e;
--search: rgba(255, 25, 255, 0.5); /* The color is pink so we can actually see it working */
}
input {
background: var(--search);
}Run Code Online (Sandbox Code Playgroud)
<input placeholder='Enter Username or Repo...'>Run Code Online (Sandbox Code Playgroud)