[css] Creating CSS Global Variables : Stylesheet theme management

Is there a way to set global variables in css such as:

@Color1 = #fff;
@Color2 = #b00;

h1 {
  color:@Color1;
  background:@Color2;
}

This question is related to css variables

The answer is


You can't create variables in CSS right now. If you want this sort of functionality you will need to use a CSS preprocessor like SASS or LESS. Here are your styles as they would appear in SASS:

$Color1:#fff;
$Color2:#b00;
$Color3:#050;

h1 {
    color:$Color1;
    background:$Color2;
}

They also allow you to do other (awesome) things like nesting selectors:

#some-id {
    color:red;

    &:hover {
        cursor:pointer;
    }
}

This would compile to:

#some-id { color:red; }
#some-id:hover { cursor:pointer; }

Check out the official SASS tutorial for setup instructions and more on syntax/features. Personally I use a Visual Studio extension called Web Workbench by Mindscape for easy developing, there are a lot of plugins for other IDEs as well.

Update

As of July/August 2014, Firefox has implemented the draft spec for CSS variables, here is the syntax:

:root {
  --main-color: #06c;
  --accent-color: #006;
}
/* The rest of the CSS file */
#foo h1 {
  color: var(--main-color);
}

I do it this way:

The html:

<head>
    <style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>

The xCss.php:

<? // place here your vars
$fntBtn = 'bold 14px  Arial'
$colBorder  = '#556677' ;
$colBG0     = '#dddddd' ;
$colBG1     = '#44dddd' ;
$colBtn     = '#aadddd' ;

// here goes your css after the php-close tag: 
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; } 

It's not possible using CSS, but using a CSS preprocessor like less or SASS.


Try SASS http://sass-lang.com/ or LESS http://lesscss.org/

I love SASS and use it for all my projects.


You will either need LESS or SASS for the same..

But here is another alternative which I believe will work out in CSS3..

http://css3.bradshawenterprises.com/blog/css-variables/

Example :

 :root {
    -webkit-var-beautifulColor: rgba(255,40,100, 0.8);
    -moz-var-beautifulColor: rgba(255,40,100, 0.8);
    -ms-var-beautifulColor: rgba(255,40,100, 0.8);
    -o-var-beautifulColor: rgba(255,40,100, 0.8);
    var-beautifulColor: rgba(255,40,100, 0.8);
 }
  .example1 h1 {
    color: -webkit-var(beautifulColor);
    color: -moz-var(beautifulColor);
    color: -ms-var(beautifulColor);
    color: -o-var(beautifulColor);
    color: var(beautifulColor);
 }