我如何将颜色定义为CSS中的variables?

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

请注意,我不能使用PHP来dynamic更改CSS文件。

CSS本地支持CSSvariables 。

示例CSS文件

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

对于一个工作的例子,请看这个JSFiddle (这个例子显示了小提琴中的一个CSSselect器被硬编码为蓝色,另一个CSSselect器使用CSSvariables,原始和当前语法,将颜色设置为蓝色) 。

在JavaScript /客户端操纵一个CSSvariables

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

支持是在所有的现代浏览器

Firefox 31 + , Chrome 49+ , Safari 9.1 + , Microsoft Edge 15+和Opera 36+都支持CSSvariables。

人们一直在回答我的答案,但是与sass或者更less的喜悦相比,这是一个可怕的解决scheme,特别是考虑到现在这两种易用的gui的数量 。 如果你有任何意识,忽略我build议下面的一切。

你可以在每个颜色之前在css中添加注释,以便作为一种variables,您可以更改使用查找/replace的值,所以…

在CSS文件的顶部

 /********************* Colour reference chart**************** *************************** comment ********* colour ******** box background colour bbg #567890 box border colour bb #abcdef box text colour bt #123456 */ 

稍后在CSS文件中

 .contentBox {background: /*bbg*/#567890; border: 2px solid /*bb*/#abcdef; color:/*bt*/#123456} 

然后,例如,更改要查找/replace的框文本的颜色scheme

 /*bt*/#123456 

CSS本身不使用variables。 但是,您可以使用另一种语言(如SASS)来定义使用variables的样式,并自动生成CSS文件,然后将其放置在Web上。 请注意,每次对CSS进行更改时,都必须重新生成生成器,但这并不困难。

没有简单的CSS唯一的解决scheme。 你可以这样做:

  • 在CSS文件中查找background-colorcolor所有实例,并为每个唯一的颜色创build一个类名称。

     .top-header { color: #fff; } .content-text { color: #f00; } .bg-leftnav { background-color: #fff; } .bg-column { background-color: #f00; } 
  • 接下来,浏览您网站上涉及颜色的每个页面,并为颜色和背景颜色添加相应的类。

  • 最后,除了新创build的颜色类以外,删除CSS中任何颜色的引用。

你可以尝试CSS3variables :

 body { var-fontColor: red; color: var(fontColor); } 

CSS的'Less'Ruby Gem看起来很棒。

http://lesscss.org/

是的,在不久的将来(我写在2012年6月),你可以定义本地的CSSvariables,而不使用更less/ sass等! Webkit引擎刚刚实现了第一个cssvariables规则,所以Chrome和Safari的尖端版本已经可以使用它们了。 查看带有现场CSS浏览器演示的官方Webkit(Chrome / Safari)开发日志 。

希望在接下来的几个月里,我们可以期待广泛的浏览器支持本地的cssvariables。

我不清楚为什么你不能使用PHP。 然后,您可以根据需要简单地添加和使用variables,将该文件另存为PHP文件,然后作为样式表而不是.css文件链接到该.php文件。

它不一定是PHP,但你明白我的意思。

当我们需要编程的东西,为什么不使用编程语言,直到CSS(也许)支持variables的东西?

另外,请查看Nicole Sullivan的面向对象的CSS 。

你可以通过javascript传递CSS,并用一定的颜色(基本上是正则expression式)replaceCOLOUR1的所有实例,并提供一个备份样式表,以防止最终用户closuresJS

dicejs.com(正式的cssobjs)是SASS的客户端版本。 您可以在CSS中设置variables(以json格式的CSS存储)并重新使用颜色variables。

 //create the CSS JSON object with variables and styles var myCSSObjs = { cssVariables : { primaryColor:'#FF0000', padSmall:'5px', padLarge:'$expr($padSmall * 2)' } 'body' : {padding:'$padLarge'}, 'h1' : {margin:'0', padding:'0 0 $padSmall 0'}, '.pretty' : {padding:'$padSmall', margin:'$padSmall', color:'$primaryColor'} }; //give your css objects a name and inject them $.cssObjs('myStyles',myCSSObjs).injectStyles(); 

这里是一个完整的下载演示的链接,这是一个更有帮助,然后他们的文档: dicejs演示

考虑使用SCSS。 它完全兼容CSS语法,所以一个有效的CSS文件也是一个有效的SCSS文件。 这使迁移变得容易,只需更改后缀。 它有许多增强function,最有用的是variables和嵌套select器。

您需要通过预处理器将其转换为CSS,然后将其发送到客户端。

多年来,我一直是一名铁杆的CSS开发人员,但是由于强迫自己在SCSS中做了一个项目,我现在不会使用其他任何东西。

如果你的系统上有Ruby,你可以这样做:

http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html

这是为Rails所做的,但请参阅下面的如何修改它以独立运行。

你可以独立于Rails使用这种方法,编写一个与site_settings.rb一起工作的小型Ruby包装器脚本,并考虑到你的CSSpath,以及每次你想重新生成CSS时你可以调用哪个在站点启动期间)

你几乎可以在任何操作系统上运行Ruby,所以这应该是相当平台独立的。

例如wrapper: generate_CSS.rb (只要你需要生成你的CSS就运行这个脚本)

 #/usr/bin/ruby # preferably Ruby 1.9.2 or higher require './site_settings.rb' # assuming your site_settings file is on the same level CSS_IN_PATH = File.join( PATH-TO-YOUR-PROJECT, 'css-input-files') CSS_OUT_PATH = File.join( PATH-TO-YOUR-PROJECT, 'static' , 'stylesheets' ) Site.generate_CSS_files( CSS_IN_PATH , CSS_OUT_PATH ) 

site_settings.rb中的generate_CSS_files方法需要像这样修改:

 module Site # ... see above link for complete contents # Module Method which generates an OUTPUT CSS file *.css for each INPUT CSS file *.css.in we find in our CSS directory # replacing any mention of Color Constants , eg #SomeColor# , with the corresponding color code defined in Site::Color # # We will only generate CSS files if they are deleted or the input file is newer / modified # def self.generate_CSS_files(input_path = File.join( Rails.root.to_s , 'public' ,'stylesheets') , output_path = File.join( Rails.root.to_s , 'public' ,'stylesheets')) # assuming all your CSS files live under "./public/stylesheets" Dir.glob( File.join( input_path, '*.css.in') ).each do |filename_in| filename_out = File.join( output_path , File.basename( filename_in.sub(/.in$/, '') )) # if the output CSS file doesn't exist, or the the input CSS file is newer than the output CSS file: if (! File.exists?(filename_out)) || (File.stat( filename_in ).mtime > File.stat( filename_out ).mtime) # in this case, we'll need to create the output CSS file fresh: puts " processing #{filename_in}\n --> generating #{filename_out}" out_file = File.open( filename_out, 'w' ) File.open( filename_in , 'r' ).each do |line| if line =~ /^\s*\/\*/ || line =~ /^\s+$/ # ignore empty lines, and lines starting with a comment out_file.print(line) next end while line =~ /#(\w+)#/ do # substitute all the constants in each line line.sub!( /#\w+#/ , Site::Color.const_get( $1 ) ) # with the color the constant defines end out_file.print(line) end out_file.close end # if .. end end # def self.generate_CSS_files end # module Site 

你可以分组select器:

 #selector1, #selector2, #selector3 { color: black; } 

不是PHP我害怕,但Zope和Plone使用类似于SASS的东西,称为DTML来实现这一点。 这在CMS中非常有用。

Upfront Systems在Plone中有一个很好的例子 。

如果您将css文件编写为xsl模板,则可以从简单的xml文件读取颜色值。 然后使用xslt处理器创buildcss。

colors.xml:

 <?xml version="1.0"?> <colors> <background>#ccc</background> </colors> 

styles.xsl:

 <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" version="1.0" encoding="iso-8859-1"/> <xsl:template match="/">body { background-color: <xsl:value-of select="/colors/background" />; } </xsl:template> </xsl:stylesheet> 

用于渲染css的命令: xsltproc -o styles.css styles.xsl colors.xml

styles.css的:

 body { background-color: #ccc; } 

当然,可以这样做,感谢多个class级的美妙世界,可以做到这一点:

 .red {color:red} .blackBack {background-color: black} 

但是我总是最终把它们结合起来,就像这样:

 .highlight {color:red, background-color: black} 

我知道语义警察会遍布你,但它的工作。

由于支持,不要使用css3variables。

如果你想要一个纯CSS的解决scheme,我会做下面的事情。

  1. 使用精确名称的颜色类。

     .bg-primary { background: #880000; } .bg-secondary { background: #008800; } .bg-accent { background: #F5F5F5; } 
  2. 从皮肤分离结构(OOCSS)

     /* Instead of */ h1 { font-size: 2rem; line-height: 1.5rem; color: #8000; } /* use this */ h1 { font-size: 2rem; line-height: 1.5rem; } .bg-primary { background: #880000; } /* This will allow you to reuse colors in your design */ 
  3. 把这些放在一个单独的css文件中,根据需要进行更改。

单独使用CSS是不可能的。

你可以用JavaScript和less来做 ,使用less.js ,这会将LESSvariables直接渲染到CSS中,但是仅用于开发,并且增加了实际使用的开销。

最接近你可以用CSS来使用属性子stringselect器,如下所示:

 [id*="colvar-"] { color: #f0c69b; } 

并将所有要调整的元素的id设置为以colvar-开头的名称,例如colvar- colvar-header 。 然后当你改变颜色时,所有的ID风格都会更新。 就像你可以单独使用CSS一样。