Css – Create a variable in .CSS file for use within that .CSS file


Possible Duplicate:
Avoiding repeated constants in CSS

We have some "theme colors" that are reused in our CSS sheet.

Is there a way to set a variable and then reuse it?


OurColor: Blue

H1 { 

Best Solution

There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so flip it around:

/* Theme color: text */
{ color: blue; }

/* Theme color: emphasis */
{ color: #00006F; }

/* ... */

/* Theme font: header */
H1, H2, H3, H4, H5, H6
{ font-family: Comic Sans MS; }

/* ... */

/* H1-specific styles */
   font-size: 2em; 
   margin-bottom: 1em;

This way, you avoid repeating styles that are conceptually the same, while also making it clear which parts of the document they affect.

Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: two attributes sharing the same value does not necessarily mean they represent the same concept. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors will vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will always share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid value repetition risks making future changes to styling incredibly error-prone; always focus on the contextual meaning of styles when looking to reduce repetition, ignoring their current values.