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

CssVariables

Css Problem Overview


> 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?

E.g.

.css
OurColor: Blue

H1 { 
 color:OurColor;
}

Css Solutions


Solution 1 - Css

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 */
H1, P, TABLE, UL
{ color: blue; }

/* Theme color: emphasis */
B, I, STRONG, EM
{ color: #00006F; }

/* ... */

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

/* ... */

/* H1-specific styles */
H1
{ 
   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.

Solution 2 - Css

You can achieve it and much more by using Less CSS.

Solution 3 - Css

No, but Sass does this. It's a CSS preprocessor, allowing you to use a lot of shortcuts to reduce the amount of CSS you need to write.

For example:

$blue: #3bbfce;
$margin: 16px;

.content-navigation {
  border-color: $blue;
  color:
    darken($blue, 9%);
}

.border {
  padding: $margin / 2;
  margin: $margin / 2;
  border-color: $blue;
}

Beyond variables, it provides the ability to nest selectors, keeping things logically grouped:

table.hl {
  margin: 2em 0;
  td.ln {
    text-align: right;
  }
}

li {
  font: {
    family: serif;
    weight: bold;
    size: 1.2em;
  }
}

There's more: mixins that act kind of like functions, and the ability to inherit one selector from another. It's very clever and very useful.

If you're coding in Ruby on Rails, it'll even automatically compile it to CSS for you, but there's also a general purpose compiler that can do it for you on-demand.

Solution 4 - Css

You're not the first to wonder and the answer is no. Elliotte has a nice rant on it: http://cafe.elharo.com/web/css-repeats-itself/. You could use JSP, or its equivalent, to generate the CSS at runtime.

Solution 5 - Css

CSS doesn't offer any such thing. The only solution is to write a preprocessing script that is either run manually to produce static CSS output based on some dynamic pseudo-CSS, or that is hooked up to the web server and preprocesses the CSS prior to sending it to the client.

Solution 6 - Css

That's not supported at the moment unless you use some script to produce the CSS based on some variables defined by you.

It seems, though, that at least some people from the browser world are working on it. So, if it really becomes a standard sometime in the future, then we'll have to wait until it is implemented in all the browsers (it will be unusable until then).

Solution 7 - Css

Since CSS does not have that (yet, I believe the next version will), follow Konrad Rudolphs advice for preprocesing. You probably want to use one that allready exists: m4

http://www.gnu.org/software/m4/m4.html

Solution 8 - Css

You're making it too complicated. This is the reason the cascade exists. Simply provide your element selectors and class your color:

h1 {
   color: #000;
}
.a-theme-color {
   color: #333;
}

Then apply it to the elements in the HTML, overriding when you need to use your theme colors.

<h1>This is my heading.</h1>
<h1 class="a-theme-color">This is my theme heading.</h1>

Solution 9 - Css

I've written a macro (in Visual Studio) that allows me to not only code CSS for named colors but to easily calculate shades or blends of those colors. It also handles fonts. It fires on save and outputs a separate version of the CSS file. This is in line with Bert Bos's argument that any symbol processing in CSS take place at the point of authoring, not not at the point of interpretation.

The full setup along with all the code would be a bit too complicated to post here, but might be appropriate for a blog post down the road. Here's the comment section from the macro which should be enough to get started.


The goals of this approach are as follows:

  1. Allow base colors, fonts, etc. to be defined in a central location, so that an entire pallete or typographical treatment can be easily tweaked without having to use search/replace

  2. Avoid having to map the .CSS extension in IIS

  3. Generate garden-variety text CSS files that can be used, for example, by VisualStudio's design mode

  4. Generate these files once at authoring time, rather than recalculating them every time the CSS file is requested

  5. Generate these files instantly and transparently, without adding extra steps to the tweak-save-test workflow

With this approach, colors, shades of colors, and font families are all represented with shorthand tokens that refer to a list of values in an XML file.

The XML file containing the color and font definitions must be called Constants.xml and must reside in the same folder as the CSS files.

The ProcessCSS method is fired by EnvironmentEvents whenever VisualStudio saves a CSS file. The CSS file is expanded, and the expanded, static version of the file is saved in the /css/static/ folder. (All HTML pages should reference the /css/static/ versions of the CSS files).

The Constants.xml file might look something like this:

<?xml version="1.0" encoding="utf-8" ?>
<cssconstants>
  <colors>
    <color name="Red" value="BE1E2D" />
    <color name="Orange" value="E36F1E" />
    ...
  </colors>
  <fonts>
    <font name="Text" value="'Segoe UI',Verdana,Arial,Helvetica,Geneva,sans-serif" />
    <font name="Serif" value="Georgia,'Times New Roman',Times,serif" />
    ...
  </fonts>
</cssconstants>

In the CSS file, you can then have definitions like:

   font-family:[[f:Text]];
   background:[[c:Background]]; 
   border-top:1px solid [[c:Red+.5]]; /* 50% white tint of red */

Solution 10 - Css

See also Avoiding repeated constants in CSS. As Farinha said, a CSS Variables proposal has been made, but for the time being, you want to use a preprocessor.

Solution 11 - Css

You can use mutliple classes in the HTML element's class attribute, each providing part of the styling. So you could define your CSS as:

.ourColor { color: blue; }
.ourBorder { border: 1px solid blue; }
.bigText { font-size: 1.5em; }

and then combine the classes as required:

<h1 class="ourColor">Blue Header</h1>
<div class="ourColor bigText">Some big blue text.</div>
<div class="ourColor ourBorder">Some blue text with blue border.</div>

That allows you to reuse the ourColor class without having to define the colour mulitple times in your CSS. If you change the theme, simply change the rule for ourColour.

Solution 12 - Css

This may sound like insanity, but if you are using NAnt (or Ant or some other automated build system), you can use NAnt properties as CSS variables in a hacky way. Start with a CSS template file (maybe styles.css.template or something) containing something like this:

a {
    color: ${colors.blue};
}

    a:hover {
        color: ${colors.blue.light};
    }

p {
    padding: ${padding.normal};
}

And then add a step to your build that assigns all the property values (I use external buildfiles and <include> them) and uses the <expandproperties> filter to generate the actual CSS:

<property name="colors.blue" value="#0066FF" />
<property name="colors.blue.light" value="#0099FF" />
<property name="padding.normal" value="0.5em" />

<copy file="styles.css.template" tofile="styles.css" overwrite="true">
    <filterchain>
        <expandproperties/>
    </filterchain>
</copy>

The downside, of course, is that you have to run the css generation target before you can check what it looks like in the browser. And it probably would restrict you to generating all your css by hand.

However, you can write NAnt functions to do all sorts of cool things beyond just property expansion (like generating gradient image files dynamically), so for me it's been worth the headaches.

Solution 13 - Css

CSS does not (yet) employ variables, which is understandable for its age and it being a declarative language.

Here are two major approaches to achieve more dynamic style handling:

  • Server-side variables in inline css
    Example (using PHP):
    > <style> .myclass{color:<?php echo $color; ?>;} </style>

 

  • DOM manipulation with javascript to change css client-side
    Examples (using jQuery library): > $('.myclass').css('color', 'blue');
    >
    > OR >

    > //The jsvarColor could be set with the original page response javascript // in the DOM or retrieved on demand (AJAX) based on user action. $('.myclass').css('color', jsvarColor);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClay NicholsView Question on Stackoverflow
Solution 1 - CssShog9View Answer on Stackoverflow
Solution 2 - CssGiorgiView Answer on Stackoverflow
Solution 3 - CssTim SullivanView Answer on Stackoverflow
Solution 4 - CsssblundyView Answer on Stackoverflow
Solution 5 - CssKonrad RudolphView Answer on Stackoverflow
Solution 6 - CssFarinhaView Answer on Stackoverflow
Solution 7 - CssDaren ThomasView Answer on Stackoverflow
Solution 8 - Cssuser4903View Answer on Stackoverflow
Solution 9 - CssHerb CaudillView Answer on Stackoverflow
Solution 10 - CssSören KuklauView Answer on Stackoverflow
Solution 11 - CssSimon ForrestView Answer on Stackoverflow
Solution 12 - CssMattView Answer on Stackoverflow
Solution 13 - CssidView Answer on Stackoverflow