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

css variables

35038 просмотра

13 ответа

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 { 
Автор: Clay Nichols Источник Размещён: 11.11.2019 02:05

Ответы (13)

89 плюса


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.

Автор: Shog9 Размещён: 06.09.2008 02:43

15 плюса

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

Автор: Giorgi Размещён: 03.04.2010 11:41

7 плюса

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;
    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.

Автор: Tim Sullivan Размещён: 06.09.2008 02:39

5 плюса

You're not the first to wonder and the answer is no. Elliotte has a nice rant on it: You could use JSP, or its equivalent, to generate the CSS at runtime.

Автор: sblundy Размещён: 06.09.2008 02:31

3 плюса

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.

Автор: Konrad Rudolph Размещён: 06.09.2008 02:26

3 плюса

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).

Автор: Farinha Размещён: 06.09.2008 03:01

2 плюса

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

Автор: Daren Thomas Размещён: 06.09.2008 02:28

2 плюса

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>
Автор: user4903 Размещён: 06.09.2008 02:45

2 плюса

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" ?>
    <color name="Red" value="BE1E2D" />
    <color name="Orange" value="E36F1E" />
    <font name="Text" value="'Segoe UI',Verdana,Arial,Helvetica,Geneva,sans-serif" />
    <font name="Serif" value="Georgia,'Times New Roman',Times,serif" />

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

   border-top:1px solid [[c:Red+.5]]; /* 50% white tint of red */
Автор: Herb Caudill Размещён: 22.09.2008 01:38

1 плюс

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.

Автор: Sören Kuklau Размещён: 06.09.2008 03:30

1 плюс

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.

Автор: Simon Forrest Размещён: 06.09.2008 08:05

1 плюс

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: ${};

    a:hover {
        color: ${};

p {
    padding: ${padding.normal};

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

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

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

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.

Автор: Matt Размещён: 06.09.2008 08:35

0 плюса

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');


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

Автор: id Размещён: 16.09.2008 05:15
Вопросы из категории :