This is as days pass by, by Stuart Langridge

And this is Variables in CSS, written , and concerning Uncategorized

Simon has a feature request for CSS3, which is the oft-heard "please let me define variables in my stylesheets" complaint. I've thought this more than once (and I'm sure I brought it up somewhere on a mailing list for discussion, too; I thought it was css-discuss, but I can't find it in the archive). So, I thought, that'd be an interesting little Javascript hack, wouldn't it; have JS look at the stylesheet rules and fix ones where you've used a "user defined variable". Ah, but no. After some testing, both Mozilla and IE just don't make invalid rules (or rulesets) available to the DOM at all. Given this stylesheet as the first and only in the document:

h1 { font-size: 1.2em; color: red; }
@media screen {
  pre { color: blue; }
}
@define {
  reddish: #f00;
}
h2 { font-size: 1.1em; color: &reddish; }
h3 { font-size: 1.0em; color: red; }
p>You'd expect document.styleSheets[0].cssRules (or ...rules for IE) to contain 5 entries, right, one for each of the rules? Nuh-uh. Walking through the rules and displaying .cssText for each (in Moz; displaying stylesheet.cssText in IE), the stylesheet looks like this:

h1 { font-size: 1.2em; color: red; }
@media screen { 
   pre { color: blue; } 
}
h2 { font-size: 1.1em; }
h3 { font-size: 1em; color: red; }

Note how both the entire invalid @define ruleset and the invalid color: &reddish rule have both been removed. No trace of them at all. So the only way I can think of making this work is to use XMLHttpRequest() (or MSXML) to grab external stylesheets, document.getElementsByTagName('style') to grab inline stylesheets, and parse them yourself. For something which will only work in very modern browsers (and not anything without XMLHttpRequest or an equivalent) with Javascript turned on, that's way, way too hard, especially since half the point of CSS is to be cross-browser and not require scripting. Since this isn't get implemented in CSS, looks like server-side parsing is the way to go. Bah. As Simon points out from the w3c-style discussion, it breaks compatibility in older browsers, although I can't see why you can't do:

h1 {
    color: red;
    color: &myred;
}

since the latter declaration is ignored by non-supporting browsers, just like all other CSS stuff.

None

Comments

GaryF

Karl, your way of doing it is really bad in terms of naming conventions. Mixing style with semantics (putting presentational information in your markup) is heavily frowned upon (and would get you shot in most CSS groups). I mean, what if you wanted .reddish to be blue. Then you have to change your CSS and HTML; bypassing one of the main advantages of CSS.

Martin

Apart from the entiy aproach, why not use correct, but non-existent colornames? Like h2 {color: myreddish;}and then parse those and replace with real values?

Karl Dubost

Another way would be to use selectors, a bit painful though.for example, you can define a reddish class.In your CSS.reddish { color: #f00;}.important { font-style: bold;}h2 { font-size: 1.1em;}And in your you HTML.

blabla

You can have more than one value separated by space in a class attribute.

Andrew Clover

Oh dear, HTML code isn't escaped on posting, that's not good. :-(Here's the example again:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" [  <!ENTITY myred "rgb(240, 16, 16)">]><html xmlns="http://www.w3.org/1999/xhtml">  <head>    <title> XML entities in stylesheets     <style>      p { color: &myred; }    </style>  </head>  <body>    <p>Hello!  </body></html>

Andrew Clover
You can do exactly this in XHTML, by defining entities:]>

Hello!

This works in Mozilla Firebird and Opera 7.2 at least. It doesn't in IE because IE doesn't parse HTML as XML. An old-style HTML parser can't do what this does, because in HTML embedded stylesheets and scripts are CDATA elements (so & means a literal ampersand).Between server-side parsing and something like this, there is really no need to bloat CSS further with a variables system.
qzio

andrew... it doesn't work for me. Im using Mozilla Firebird

ekkis [e@arix.com]

it occurred to me I might be able to use expression to implement variables… what I did was to set a non-existent attribute in any given id/class/tag. I can then use it anywhere else as shown below. the code below works in IE:




testing



I used body in the code above because originally I used a throwaway class to do this and found it wouldn’t work unless I applied the class to some object i.e. the code below wouldn’t work without the div using the class.




testing

ekkis [e@arix.com]

damned site. ate my code. anyone wishing to see the solution, read the source to this page.

ekkis [e@arix.com]

further testing revealed that this simpler solution also works great:

@


testing

@

ekkis [e@arix.com]

I see the site ate my code again, even though I put it in between @s. grr…

here’s another try:




testing

ekkis [e@arix.com]

I surrounded the code above in XMP tags but the site added paragraghs and breaks. A note to the webmaster: this is a site for developers, pasting code is LIKELY TO HAPPEN. For God’s sakes, make it easy!

sil

Expressions in CSS only work in IE, and they require JavaScript, both of which knock your suggestion out as a cross-platform solution.
I am aware that code posting needs to be fixed. One day I’ll get round to it.

x

x

k

Michael

Why not write an extension for IIS that pre-processes .CSS files when they’re requested from the server? The pre-processor could scan for marked variables and replace them from a known data source, such as a global variables file. I’d bet such a thing already exists in the public domain…

[Starts searching Google…. ]

Matthew Robinson

i'd like css variables too, but it can be done using multiple classes. in the html just set:

<mytag class="originaltag backgrouncolor">

css:

.backgrouncolor{

background-color:#fff; /*or whatever*/

}

mc

Michael:

instead of the extension, you might want to write your CSS files as .ASP files, and thereby have the IIS preprocessor take care of them like any other dynamically generated page.

We've used this in our dept. for small-medium scale projects for quite some time (or a similar principle in PHP). However, rather than using *variables* per se, we define constants for CSS.

MC

Yves

No variables in CSS! don't know what the CSS guys do all day long :(

Using PHP you can simulate variables in CSS, like

This works fine. The only drawback is that PHP has to process each line from the echo to the final CSSCODE; instead of simply printing out the lines (if it there was no variable, and the code would not be between ) .

Yves

Using the &lt; and gt...

No variables in CSS! don't know what the CSS guys do all day long :(

Using PHP you can simulate variables in CSS, like

<?php

$mycolor = '#f11';

$mywidth = 123 + 456;

echo <<<CSSCODE

div.mystuff { background-color: $mycolor; width: ${mywidth}px; }

CSSCODE;

?>

This works fine. The only drawback is that PHP has to process each line from the echo to the final CSSCODE; instead of simply printing out the lines (if it there was no variable, and the code would not be between <?php ?> ) .

Rodrigo Contreras K.

Take a look at my alternative implementation of CSS variables here:

http://www.simov.cl/rc/blog/?page_id=115

Christopher C

Thanks to all, very useful. I will implement a totally valid xhtml and css site in http://www.comucom.com with this help.

Phil

What about using an include file instead of the css file. You can call the include file into any template in a similar manner to calling the css file.

inside this include file, you have your CSS code with variables . Save the file as php / asp, and you're all set.

Does this make sense? It seems like it will work.

NightAngel.fr» Blog Archive » Définir des variables en CSS ?

[...] Les feuilles de style CSS sont utilisées pour décrire la présentation d’un document structuré écrit en HTML ou en XML. De part cette fonction de présentation, on en déduit qu’il est donc nativement impossible de définir des variables dans une CSS. Après quelques recherches je remarque que des utilisateurs ont déjà fait part de cette idée pour CSS3. Quoiqu’il en soit, visiblement, tout le monde fait la sourde oreille ! Ne cherchant pas à rendre possible ce qui est jusque là impossible, j’ai donc décidé de contourner le problème. Et là, la brillante idée de générer ma CSS dans un langage interprété côté serveur m’est apparue Mon choix est fait, ma CSS sera générée en PHP (troll facultatif). En effet il aurait été possible de générer ma CSS dans un langage interprété côté client (comme le Javascript) mais visiblement cela pose quelques problèmes. [...]

gfhgfhgfhgfh

gfgfhgfhghgfhgfhgfhfghfgh

This website belongs to Stuart Langridge. Contact details are available. Don't eat yellow snow. Valid HTML5, at least in theory, except for the bits that aren't because I'm that futuristic that I'm ahead of the spec, oh yes. HTML5 help from Bruce Lawson, among others. Fonts from the superb FontSquirrel. End.