Christian Heilmann

CSS constants

Friday, February 11th, 2005 at 2:17 am

A lot of web designers complain about CSS lacking constants you could define once and reuse throughout the CSS document. CSS was not meant for that and does not support it.
What you can do though is use a server side language to simulate a CSS file by setting the appropriate header. However, this means you need to stick to the language syntax.

Playing with that idea, I came up with a small PHP script that parses any CSS given to it via a variable and reads and replaces the defined constants in the CSS.

This page shows how it can be used. You apply the CSS with the invalid constants syntax by looping it through the PHP script:

In the CSS file, you define the constants with the following syntax:
$colour1 = '#999';
$colour2 = '#363';
$colour4 = '#696';
$colour3 = '#cfc';

And you can use them throughout the whole CSS document:

#footer{
padding:.2em .5em;
margin:0;
background:$colour1;
}

Any improvements?

I am aware that this is butchering the idea of CSS as presentation only, and means you design invalid CSS in the raw form, but it fills a gap and it might make CSS maintenance a bit easier. You can still validate your CSS by looping it through the script:
http://icant.co.uk/articles/cssconstants/cssconst.php?c=demo.css.

Share on Mastodon (needs instance)

Share on BlueSky

Newsletter

Check out the Dev Digest Newsletter I write every week for WeAreDevelopers. Latest issues:

160: Graphs and RAGs explained and VS Code extension hacks Graphs and RAG explained, how AI is reshaping UI and work, how to efficiently use Cursor, VS Code extensions security issues.
159: AI pipelines, 10x faster TypeScript, How to interview How to use LLMs to help you write code and how much electricity does that use? Is your API secure? 10x faster TypeScript thanks to Go!
158: 🕹️ Super Mario AI 🔑 API keys in LLMs 🤙🏾 Vibe Coding Why is AI playing Super Mario? How is hallucinating the least of our worries and what are rules for developing Safety Critical Code?
157: CUDA in Python, Gemini Code Assist and back-dooring LLMs We met with a CUDA expert from NVIDIA about the future of hardware, we look at how AI fails and how to play pong on 140 browser tabs.
156: Enterprise dead, all about Bluesky and React moves on! Learn about Bluesky as a platform, how to build a React App and how to speed up SQL. And play an impossible game in the browser.

My other work: