Obsidian Obsidian - 5 months ago 17
CSS Question

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

Answer

Latest Update: 20/06/2016

CSS Global variables have arrived!

Another year another browsers. Google has now joined Mozilla by supporting this truely great feature.

YOU CAN NOW VOTE ON THIS FOR I.E DEVELOPMENT


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 a variable:

:root {
    --bgd: #333;
}

Add names for your variable followed by a value:

(names can be any string you choose.)

: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

enter image description here

FIREFOX: Version 31+ (Enabled by default)

(Leading the way as usual.) More info from Mozilla

CHROME: Version 49+ (Enabled by default).

"This feature can be enabled in Chrome Version 48 for testing by enabling the experimental Web Platform feature. Enter chrome://flags/ in your Chrome address bar to access this setting."

IE/Edge: Under consideration.

"You can now vote on this to pump it up the development road map"

VOTE HERE

IE ROAD MAP

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

Opera: Under development.

VIEW FULL SUPPORT LIST


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>