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

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


当前回答

由于支持,不要使用css3变量。

如果你想要一个纯css解决方案,我会做以下事情。

Use color classes with semenatic names. .bg-primary { background: #880000; } .bg-secondary { background: #008800; } .bg-accent { background: #F5F5F5; } Separate the structure from the skin (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 */ Put these inside a separate css file to change as needed.

其他回答

Yeeeaaahhh……你现在可以在CSS.....中使用var()函数

好消息是你可以使用JavaScript访问来改变它,这也会在全局范围内改变…

但是如何申报呢?

这很简单:

例如,你想要将#ff0000赋值给var(),只需简单地将它赋值在:root中,还要注意——:

:root {
    --red: #ff0000; 
}

html, body {
    background-color: var(--red); 
}

好的方面是浏览器支持不差,也不需要像LESS或SASS那样编译才能在浏览器中使用…

另外,这是一个简单的JavaScript脚本,它将红色值更改为蓝色:

const rootEl = document.querySelector(':root');
root.style.setProperty('--red', 'blue');

CSS本身不使用变量。但是,你可以使用另一种语言,比如SASS,用变量来定义你的样式,并自动生成CSS文件,然后你可以把它放在网上。注意,每次对CSS进行更改时都必须重新运行生成器,但这并不难。

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

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

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

通过编写一个小型Ruby包装器脚本,您可以独立于Rails使用这个方法 它与site_settings一起工作。rb,并将css路径考虑在内 你可以在每次你想重新生成CSS的时候调用它(例如在网站启动期间)

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

例如,包装器: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中的generate_CSS_files方法。然后Rb需要修改如下:

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 , e.g. #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

编辑:这个答案不再是最新的。你现在应该使用CSS变量。

考虑使用SCSS。它与CSS语法完全兼容,因此有效的CSS文件也是有效的SCSS文件。这使得迁移很容易,只需要更改后缀。它有许多增强,最有用的是变量和嵌套选择器。

在将其发送到客户端之前,需要通过预处理器将其转换为CSS。

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

是的,在不久的将来(我在2012年6月写了这篇文章)你可以定义原生css变量,而不需要使用更少的/sass等!Webkit引擎刚刚实现了第一个css变量规则,所以Chrome和Safari的前沿版本已经可以使用它们了。查看官方Webkit (Chrome/Safari)开发日志和现场css浏览器演示。

希望在接下来的几个月里,我们可以看到浏览器对原生css变量的广泛支持。