Bill asks the CSS Guy if there is a way to use variables within CSS

Bill writes:

One thing I am not certain how to do, or if it is even possible is to define some sort of pseudo-variable that can be used in the CSS definitions. For example, I am working on a page that the owners want a specific color scheme used throughout the site. Each page has five colors (they all share the same set of colors). CSS has made my life sooo much easier to make changes they want (they are making several changes a day trying to “fine tune” the exact shades they want.

Anyway, it would be nice if I could do something like this:

#Red1 { color: #400000 }
#Cream1 { color: #F0E68C }
#Cream2 { color: #FAFAD2 }
#Blue1 { color: #00008B}

and then further in the CSS file uses these names like:

body {
  color: Blue1;
}
 
a {
  color: Red1;
}
 
a.footer {
  color: Cream2;
}

Bill, the short answer is no. CSS isn’t built for that. Your editor’s find and replace is your surest bet.

However, there is a longer answer, too. Many people have wanted this feature, and have found a way to make it happen using server-side scripting.

Please see this entry on 24ways.org for a well-written and relatively recent article on your options to achieve this. The comments themselves are enlightening as well. The last comment on that article has a link to a post that is particularly helpful in understanding why this feature wasn’t included in CSS to begin with.

My advice is to stick to find and replace.


This post was ported from an old host and CMS, so many comments were lost. Below are the comments that I found were most helpful regarding this post that I salvaged. Some links or attributions may not be working correctly.


pahtrick said:
http://www.designrefugee.com/design-blog/css-variables.html
for a comprehensive tutorial on PHP parsing & variables in CSS