88

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

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

h1 {
  color:@Color1;
  background:@Color2;
}
cimmanon
  • 67,211
  • 17
  • 165
  • 171
DreamTeK
  • 32,537
  • 27
  • 112
  • 171
  • 1
    CSS hasn't got variables, you need to use a preprocessor. – MMM Apr 05 '13 at 10:36
  • http://stackoverflow.com/questions/7247202/how-to-use-variable-in-css please read this thread – muneebShabbir Apr 05 '13 at 10:36
  • So easy to google it http://css3.bradshawenterprises.com/blog/css-variables/ – Griffin Apr 05 '13 at 10:36
  • 3
    Thanks for the link to the spec. I should mention that it has been updated (5 May 2014). It now uses `--red: #b00;` and (a more convoluted) `color: var(--red);` instead of the old `var-red: #b00;` and (a more straightforward) `color: var(red);`. Firefox 31, which will probably be released the around the beginning of August 2014, has already been modified to reflect the new specs. It is the first (and currently only) browser to list support as standard. The partial/hacked support was removed from Chrome's blink engine (pending some rewrites), but it appears that WebKit (v.528+) has support. – jbo5112 May 20 '14 at 17:15

6 Answers6

181

Latest Update: 16/01/2020

CSS Custom Properties (Variables) have arrived!

It's 2020 and time to officially roll out this feature in your new applications.


Preprocessor "NOT" required!

There is a lot of repetition in CSS. A single color may be used in several places.

For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally.

For non-trivial projects, this is not always possible. By declaring a variable on the :root pseudo-element, a CSS author can halt some instances of repetition by using the variable.

How it works

Set your variable at the top of your stylesheet:

CSS

Create a root class:

:root {
}

Create variables (-- [String] : [value])

:root {
  --red: #b00;
  --blue: #00b;
  --fullwidth: 100%;
}

Set your variables anywhere in your CSS document:

h1 {
  color: var(--red);
}
#MyText {
  color: var(--blue);
  width: var(--fullwidth);
}

BROWSER SUPPORT / COMPATIBILITY

See caniuse.com for current compatability.

![supported browsers


Firefox: Version 31+ (Enabled by default)

Supported since 2014 (Leading the way as usual.)

More info from Mozilla


Chrome: Version 49+ (Enabled by default).

Supported since 2016


Safari/IOS Safari: Version 9.1/9.3 (Enabled by default).

Supported since 2016


Opera: Version 39+ (Enabled by default).

Supported since 2016


Android: Version 52+ (Enabled by default).

Supported since 2016


Edge: Version 15+ (Enabled by default).

Supported since 2017

CSS Custom Properties landed in Windows Insider Preview build 14986


IE: When pigs fly.

It's time to finally let this ship sink. No one enjoyed riding her anyway. ☺


W3C SPEC

Full specification for upcoming CSS variables

Read more


TRY IT OUT

A fiddle and snippet are attached below for testing:

(It will only work with supported browsers.)

DEMO FIDDLE

:root {
  --red: #b00;
  --blue: #4679bd;
  --grey: #ddd;
  --W200: 200px;
  --Lft: left;
}
.Bx1,
.Bx2,
.Bx3,
.Bx4 {
  float: var(--Lft);
  width: var(--W200);
  height: var(--W200);
  margin: 10px;
  padding: 10px;
  border: 1px solid var(--red);
}
.Bx1 {
  color: var(--red);
  background: var(--grey);
}
.Bx2 {
  color: var(--grey);
  background: black;
}
.Bx3 {
  color: var(--grey);
  background: var(--blue);
}
.Bx4 {
  color: var(--grey);
  background: var(--red);
}
<p>If you see four square boxes then variables are working as expected.</p>

<div class="Bx1">I should be red text on grey background.</div>
<div class="Bx2">I should be grey text on black background.</div>
<div class="Bx3">I should be grey text on blue background.</div>
<div class="Bx4">I should be grey text on red background.</div>
Community
  • 1
  • 1
DreamTeK
  • 32,537
  • 27
  • 112
  • 171
  • Even now preprocessors are still the way forward until everyone starts using modern browsers. – BlueEyesWhiteDragon Apr 13 '16 at 10:32
  • 1
    @BlueEyesWhiteDragon Unfortunately this is the nature of web development and as some user still use IE6 it could be another ten years before the approach is practical. It is our duty as developers to push browser updating to users wherever it is practical. People will continue to use outdated browsers as long as we continue to support them! – DreamTeK Apr 13 '16 at 10:53
  • @Obsidian I dropped IE 8 & 9 support a while back, IE 10 seems modern enough to still support however... – BlueEyesWhiteDragon Apr 13 '16 at 14:20
  • I wonder why don't they allow us to declare variables with `var(test)` then use those variables along with a special character, may be something like `@test` or `$test`. Woundn't it be more convenient? – Lewis Oct 24 '16 at 17:07
  • @Tresdin Yes it would be more convenient. The problem is CSS has already allocated both of those symbols for other uses along with nearly all special characters. I believe double hyphen(--) was chosen because a new declaration was required. – DreamTeK Oct 25 '16 at 09:37
  • @Obsidian The actual problem is that you have to write `var(...)` anytime you want to use a variable. I think that's terribly inconvenient. Your point makes sense though. – Lewis Oct 25 '16 at 10:35
  • @Tresdin This was my thinking too. The initial spec was simply --var but they changed it. I can only assume there was a good reason. Hopefully the time that will be saved when we can actually use variables will be worth it! :) – DreamTeK Oct 25 '16 at 10:38
  • 1
    IE: It's never going to happen. – garish Dec 31 '19 at 08:22
  • Am I allowed to use :root in several css files and does every work. And what if a value is declared in two seperade :root declarations twice? – CAoT Jan 14 '22 at 00:22
  • @CAoT I havn't tested but I suspect several root classes would be fine, following specificity rules. – DreamTeK Jan 14 '22 at 14:46
32

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);
}
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • Thanks will take a look. What is the cross browser compatibility? – DreamTeK Apr 05 '13 at 10:39
  • Well it compiles to CSS, so you write it (.scss file), build it (into a .css file) and then include it in your application just like a regular stylesheet. So compatibility is as good as CSS :) I highly recommend it, it makes writing CSS so much more fun. – Daniel Imms Apr 05 '13 at 10:40
  • @DanielImms is on fire this week. CSS variables are coming but how long will IE take to implement them. – SomeShinyObject Apr 05 '13 at 10:54
  • @Christopher well, IE11 maybe.. As for when we would be able to use them though... I hope MS change their release cycle and start doing silent updates soon. – Daniel Imms Apr 05 '13 at 10:56
7

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

deceze
  • 510,633
  • 85
  • 743
  • 889
4

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

I love SASS and use it for all my projects.

joshuahornby10
  • 4,222
  • 8
  • 36
  • 52
4

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; ?>; } 
Helmo56
  • 49
  • 3
2

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);
 }
Rahul Patil
  • 5,656
  • 6
  • 37
  • 65