tags:

views:

511

answers:

6

Are there any useful techniques for reducing the repetition of constants in a CSS file?

(For example, a bunch of different selectors which should all apply the same colour, or the same font size)?

A: 

You can use multiple inheritance in your html elements (e.g. <div class="one two">) but I'm not aware of a way of having constants in the CSS files themselves.

This link (the first found when googling your question) seems to have a fairly indepth look at the issue:

http://icant.co.uk/articles/cssconstants/

samjudson
+3  A: 

You should comma seperate each id or class for example:

h1,h2 {
color: #fff;
}
KevinUK
+1  A: 
Zack Peterson
+4  A: 

Elements can belong to more than one class, so you can do something like this:

.DefaultBackColor
{
    background-color: #123456;
}
.SomeOtherStyle
{
    //other stuff here
}
.DefaultForeColor
{
    color:#654321;
}

And then in the content portion somewhere:

<div class="DefaultBackColor SomeOtherStyle DefaultForeColor">Your content</div>

The weaknesses here are that it gets pretty wordy in the body and you're unlikely to be able to get it down to listing a color only once. But you might be able to do it only two or three times and you can group those colors together, perhaps in their own sheet. Now when you want to change the color scheme they're all together and the change is pretty simple.

But, yeah, my biggest complain with CSS is the inability to define your own constants.

Joel Coehoorn
+1  A: 

Personally, I just use comma-separed selector, but there some solution for writing css programmatically. Maybe this is a little overkill for you simpler needs, but take a look at CleverCSS (Python)

fcurella
A: 

CSS Variables, if it ever becomes implemented in all major browsers, may one day resolve this issue.

Until then, you'll either have to copy and paste, or use a preprocessor of whatever sort, like others have suggested (typically using server-sider scripting).

Sören Kuklau