如何在 CSS 中将颜色定义为变量? [英] How can I define colors as variables in CSS?

查看:48
本文介绍了如何在 CSS 中将颜色定义为变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个很长的 CSS 文件.我知道客户可能会要求更改配色方案,并且想知道:是否可以将颜色分配给变量,以便我可以更改一个变量以将新颜色应用于所有使用它的元素?

请注意,我无法使用 PHP 来动态更改 CSS 文件.

解决方案

CSS 通过 原生支持这一点CSS 变量.

示例 CSS 文件

:root {--主色:#06c;}#foo {颜色:var(--main-color);}

有关工作示例,请参阅this JSFiddle(该示例显示了小提琴将颜色硬编码为蓝色,另一个 CSS 选择器使用 CSS 变量(原始语法和当前语法)将颜色设置为蓝色).

在 JavaScript/客户端操作 CSS 变量

document.body.style.setProperty('--main-color',"#6c0")

支持所有现代浏览器

Firefox 31+Chrome 49+Safari 9.1+Microsoft Edge 15+Opera 36+ 附带对 CSS 变量的原生支持.

I’m working on a CSS file that is quite long. I know that the client could ask for changes to the color scheme, and was wondering: is it possible to assign colors to variables, so that I can just change a variable to have the new color applied to all elements that use it?

Please note that I can’t use PHP to dynamically change the CSS file.

解决方案

CSS supports this natively with CSS Variables.

Example CSS file

:root {
    --main-color:#06c;
}

#foo {
    color: var(--main-color);
}

For a working example, please see this JSFiddle (the example shows one of the CSS selectors in the fiddle has the color hard coded to blue, the other CSS selector uses CSS variables, both original and current syntax, to set the color to blue).

Manipulating a CSS variable in JavaScript/client side

document.body.style.setProperty('--main-color',"#6c0")

Support is in all the modern browsers

Firefox 31+, Chrome 49+, Safari 9.1+, Microsoft Edge 15+ and Opera 36+ ship with native support for CSS variables.

这篇关于如何在 CSS 中将颜色定义为变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆