Anyone even slightly familiar with a programming language will have come across the concept of constants – a fixed value that can be used through your code. For example, in a PHP script I might have a constant which is the email address that all emails generated by my application get sent to.
$adminEmail = 'info@example.com';- Source: /code/faster-development-with-css-constants/constant1.txt
I could then use $adminEmail in my script whenever I wanted an email to go to that address. The benefit of this is that when the client decides they want the email to go to a different address, I only need change it in one place – the place where I initially set the constant. I could also quite easily make this value user defined and enable the administrator to update the email address.
Unfortunately CSS doesn’t support constants. It would be really useful to be able to define certain values initially and then use them throughout a CSS file, so in this article I’m going to take a look at some of the methods we do have available and provide pointers to more in depth commentary on each. If you have a different method, or tip to share please add it to the comments.
So what options do we have?
One way to get round the lack of constants is to create some definitions at the top of your CSS file in comments, to define ‘constants’. A common use for this is to create a ‘color glossary’. This means that you have a quick reference to the colors used in the site to avoid using alternates by mistake and, if you need to change the colors, you have a quick list to go down and do a search and replace.
In the below example, if I decide I want to change the mid grey to #999999, all I need to do is search and replace #666666 with #999999 – assuming I’ve remember to always use that value for things which are mid grey.
/*Dark grey (text): #333333Dark Blue (headings, links) #000066Mid Blue (header) #333399Light blue (top navigation) #CCCCFFMid grey: #666666*/- Source: /code/faster-development-with-css-constants/glossary.txt
This is a fairly low-tech method, but if used throughout the development of the CSS files can make changes far simpler and help to ensure consistency in your color scheme.
I’ve seen this method used by many designers however Garrett Dimon documents the method, with more ideas in the comments.
Going server-side
To truly achieve constants you will need to use something other than CSS to process the file before it is sent to the browser. You can use any scripting language – PHP, ASP, ColdFusion etc. to parse a CSS file in which you have entered constants. So that in a constants section of the CSS file you would have:
$darkgrey = '#333333';$darkblue = '#000066';- Source: /code/faster-development-with-css-constants/constant2.txt
The rest of the CSS file is as normal except that when you come to use the constant value you would use the constant name instead of adding the color:
p {color: $darkgrey;}- Source: /code/faster-development-with-css-constants/cssrule.txt
Your server-side script could then parse the CSS file, replace the constant names with the constant values and serve a valid CSS file to the browser. Christian Heilmann has done just this for PHP however this could be adapted for any language you might have available on your server.
Shaun Inman came up with another way
of doing this that removes the need to link to a PHP script and also enables the adding of constants using the syntax of at-rules . This method is again using PHP and will require you to edit an .htaccess file.
A further method is to generate static CSS files either using a script locally – if the constants are just to enable speed of development – or as part of the web application itself. Storing a template stylesheet with constant names in place of the values you will want to update means that your script can simply open the template, replace the variables and save the result as a new stylesheet file.
While CSS constants are a real help to developers, they can also be used to add new functionality to your applications. As with the email address example that I used at the beginning of this article, using a combination of CSS and server-side scripting you could enable a site administrator to select the colours for a new theme to be used on a page of a content managed site. By using constants you need only give them the option to change certain parts of the CSS and not upload a whole different CSS file, which could lead to some interesting results!
As we are unlikely to find real CSS constants under the tree this Christmas the above methods are some possibilities for better management of your stylesheets. However if you have better methods, CSS Constant horror stories or any other suggestions, add your comments below.


Comments
02/12/2006
How about
h1 { font-size: 200%; }
em { font-width: bold; }
/* blue stuff */
h1, em, ul#head li, ul#head li li { color: rgb(0,0,255); }
Would be it, ha ? And even without server side scripting and with no redundancy.
so long,
Peritus
02/12/2006
Hi Rachel. I read this article and I agree at some point, but for a principle I believe that CSS don’t need to be mixtured with PHP or other scripting language. Why? I just use the ‘find & replace’.
>‘using a combination of CSS and server-side scripting you could enable a site administrator to select the colours >for a new theme to be used on a page of a content managed site.’
I really don’t believe that the ‘site administrator’ can be mixing colors. I do believe that is the job of the designer.
Btw, I just bought your book HTML Utopia: Designing Without Tables Using CSS and I’m loving it.
02/12/2006
This article is really cool, I never used constants in CSS, but now reading this I think it can be very usefull
Thank you!
02/12/2006
>Peritus:
>h1 { font-size: 200%; }
>em { font-width: bold; }
>/* blue stuff */
>h1, em, ul#head li, ul#head li li { color: rgb(0,0,255); }
Imagine how messy that would become on even a smal scale projekt. – I cant see why CSS dont have constants by default tho. That would have been one of the first things I’d put in. And it doesn’t seem like it will be added. A shame.. – whats up with no quote markup in comments? No markup at all!
02/12/2006
@ Jorge – I think it’s a fairly rare thing that you might want to expose some of the CSS to the site admin, but I’ve had just this situation recently at work. The method we went with was generating static stylesheets (using PHP) for each color theme (the admin could set 3 main colors, background image and repeat) and it works well. It’s a very specific usage though. However, what about creating a photo gallery site where photographers can customize their album page by changing the background and color theme? Sites like Yahoo Groups enable the group owner to customize the color scheme to an extent to individualize their community so I think there are places where generating CSS is useful and appropriate. I don’t think it’s something you’d want to sling into every CMS though!
02/12/2006
A bit out of this topic but might be helpful for the PHP part :
Real constants, not variables, exists indeed in PHP
define(“CONSTANT_NAME”,“constant value”);
I usually use it to define the installation path of my sites, this allows me to easily move a site into subfolders.
define(‘INSTALL_PATH’, ‘/folder-name’);
$url = INSTALL_PATH.’/path/of/the/files’;
Also, the constant name doesn’t need to be in full uppercase but it makes it easier to spot in your code later.
As for the CSS constant this seems a nice to go, specially on big files or if you work in a team.
02/12/2006
To follow from Fabrice, what you have in that first code snippet is not a constant but in fact a variable. Variables can change (they are variable), constants are constant.
Anyways, enough picking nits, CSS constants are very useful!!
02/12/2006
Great article. I’ll try this.
Every CMS are capable of managing article but not of CSS itself.
I wish I could edit CSS dynamically using PHP through CMS.
03/12/2006
The comments about variables vs. constants are quite correct. Also, I wrote a little more detailed article on the technique of using PHP to generate CSS on Digital Web. Check it out if you’re interested:
http://www.digital-web.com/articles/generating_dynamic_css_with_php/
03/12/2006
A ‘constant’ is a fixed value that cannot be changed at run-time – if the values you are setting are fixed as in the examples above then I think constant is the correct term. If you are allowing them to be altered by the user – for example dynamically setting a background color – then you would be correct in calling them variables. My primary reason for using the word constant over variable is that most of the existing discussion on the web uses ‘CSS Constants’ as the term to describe this concept, I find it helps if you give someone a phrase they can search on and get results.
@ Douglas – thanks for the link to the article, that’s another useful resource for this.
03/12/2006
Hi,
I mostly agree with the discussion about constants and also i do like the idea behind it. It certainly is something you will need to use when you offer the community of a site to change style values according to their preferences. Otherwise i would not so much try to mix any other scripting language together with CSS.
I would love to have CSS constants, agreed. Just creating a workaround so that i have it simpler with color values sounds a bit overshot for me though. You might be using those colors, or CSS definitions multiple times, but unless there are real constants i would certainly not try to splice PHP into that mix.
I think this is a very specific use and it should NOT be adapted for daily use on the usual flok of websites.
03/12/2006
Without wishing to draw the pointless debate out further, the concept of a constant exists regardless of any particular features of any particular language. It’s a value that you set once and then get many times. Some languages give you protected ways of doing that, some don’t. You can use those features if you wish, or choose not to.
Either way it’s a completely irrelevant tangent, so let’s drawn a line under that particular debate, folks.
03/12/2006
Wow, don’t mix CSS with PHP (or any server side scripting language for that matter) unless you know what you’re doing. Using a generated CSS file really increases the amount of bandwidth being consumed. This is because static files (like normal .css files) are cached while generated files are not. So if you go to a website that generates the stylesheet using a server side scripting language, you have to download the stylesheet every time you visit a page on that particular website. If this website chose to use a static file instead, this would not be the case because the file would’ve been cached. Therefore, if you choose to generate your stylesheet using a server side scripting language, make sure you implement a good caching mechanism.
On the other hand, I do agree that CSS should have an option to declare constants. Unfortunately, the W3C doesn’t think this way, judging by this message.
03/12/2006
I hacked the CSS for my site for the first time last week, and I was amazed and disappointed that the language didn’t include constants.
It makes so much sense.
03/12/2006
Jero, you’re right that if you’re generating the CSS at runtime you need to make sure you’re serving it with the correct headers. Depending on circumstance, I think the more common scenario is to generate your CSS when it changes and save that as a static file on the file system.
Just as with any server-side scripting, it’s wasteful to generate the same file again and again when you know it hasn’t changed. The exact same statement applies to generating an HTML document.
04/12/2006
Long time ago in a galaxy far, far away… wait, that’s a completely different story. Let’s start again: in the past millenium I used something called HSC. It was an HTML preprocessor, that gave me an idea for the solution, that works for me now.
Needed tools:
* SVN (or any version control system of your choice; it’s not essential, but you’ll still have to use the scripts …and after all, what sane person doesn’t use some VCS anyway?),
* conversion table – e.g. in (keyword:value\n)* format,
* custom commit script that runs keyword->value conversion on *.css files and then commits,
* second script that converts value->keyword on update.
Instead of svn commands, I use the custom scripts as Total Commander buttons or CLI commands. This way I have the keywords where I need them (my working copy) and keep the code in repository clean, so no server-side scripting is needed.
The scripts can use local (every developer may have own keywords in her/his working copy) or global conversion table.
You can use it for more than colours (i.e. images), but it may be not 100% update-safe.
Of course there are some limitations:
- you have to commit changes to see them (not a minus for me, but you may want to create a script that will export a local preview),
- lossy conversion on update (you can’t have more than one keyword for one value),
- you can use the keywords only in external style sheets or face a serious mess if you try to run the conversions on all files (again, not a minus for me, and in my library I have header_style() and inline_style() functions that use the global conversion table if I really, really need it; not recommended, though).
Hope someone finds this helpful.
04/12/2006
Wow !
I didn’t want to start a debate, just pointed out a useful function in PHP.
Sorry for that.
04/12/2006
Just a quick thought:
When using the first technique of including a color glossary, make sure you use full hexadecimal values, not the 3-character shortcuts.
Searching and replacing “#666” when you also use colors like ‘#666000’ would be disastrous ;)
06/12/2006
Don’t get it. Didn’t we learn in css to not use specifics like “darkgrey” or “leftnavigation” or “blueheader”...? Now you add $darkgrey to your css file. If you want to change that to dark blue wouldn’t you need to replace all the $darkgrey with $darkblue? Or change $darkgrey = ‘#333333’ to ‘#000066’ but then it isn’t darkgrey anymore.
Wouldn’t it make more sense naming your constant $textcolor (or just $color) or something?
06/12/2006
Halans – that’s a fair point, I think. Using semantic names for the constants is probably a good idea.
However, there’s a big difference between naming constants within a CSS file and choosing class names or IDs within a document. A key idea behind separating content and styling is that you can change one without affecting the other. You can redesign your site (to turn the greys blue or whatever) by attaching a new stylesheet to the document. That stylesheet in turn would have its own constants with their own names.
Those constants are restricted to the scope of the stylesheet where they are truly appropriate. The presentation layer (CSS) is exactly where it’s okay to talk of how something looks.
06/12/2006
Since you might use the same color for two different “constants”, it’d be safer to append a comment to each value:
body {color : #ffffff /*mainTextColor*/; }
...
p {color: #ffffff /*secondaryTextColor*/; }
Now when you want to alter just the “mainTextColor” you’ll be able to do so w/ find/replace.
11/12/2006
If you’re going to mix CSS with PHP you’d better do it right. :) If you control the server you can use more fancy methods, but you’d be well advised to turn your .css files into .php on shared hosting.
One (obvious?) benefit is being able to define constants or variables. Colors are just one application. Another are widths, be they pixels or percentages or whatever. Define your main content area as 75% and your sidebar as 25%, or the main as 400px and the sidebar as 120px and you can use PHP to spread those values all around the CSS and even do calculations on the fly based on them.
Another great benefit is adding HTTP headers for gzip compression and timestamping, to facilitate caching and to reduce bandwidth. CSS is pure text so it compresses very well. You’ll be able to reduce that 20k CSS file to only 1-2k that each visitor has to transfer.
22/12/2006
It seems like what you’re really talking about is the ability to easily change things globally. Something I do that makes this easier is to have sections in my CSS for color information and font information, so that at least these attributes are grouped for easy editing. This could be taken further by grouping other attributes such as borders, layout information, etc. When all of your colors are in one, scannable section of your CSS, it’s relatively easy to make a global change.
24/12/2006
I posed the question as to why constants aren’t supported in CSS to Hakon Wium Lie, the “father of CSS,” back in April…and he answered:
http://www.bernzilla.com/item.php?id=666
24/07/2009
I am fairly ambivalent towards the use of constants generally in CSS due to the convenience vs performance dilemma however I do believe that constants should be allowed in the case of the following statement type:
background: url(https://10.10.10.10/img/myimage.png) bottom right no-repeat;
where one references external image files within the CSS file itself – in my opinion it is completely redundant and potentially dangerous to have to re-reference a path location again and again if you are using a particular path to store image files in that are referenced as styles
In fact in this context i feel fairly strongly that one should be able to pass parameters in the CSS file call as it would then allow one to flexibly determine where external files called from within the CSS file will live …but alas i is not to be
Impress us