Creating CSS Global Variables
What is CSS Variable?
CSS Variables are entities defined by authors, or users, of Web pages to contain specific values throughout a document. They are set using custom properties and are accessed using a specific functional notation var().
What problems to solve with CSS variable?
When building large sites, authors often face a maintainability challenge. In such websites, the size of the CSS is quite large and a lot of information may be repeated in multiple places. For example, maintaining a coherent color scheme throughout a document implies reusing a few color values at numerous positions in the CSS files. Altering the scheme, whether tweaking a single color or completely rewriting it, therefore becomes a complex task requiring precision, as a single find and replace often isn't enough.
A second advantage of these variables is that the name itself contains semantic information. CSS files become easier to read and understand: main-text-color is easier to understand than the reuse of #00ff00 throughout the text, especially if this same color is also used in another context.
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
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.
Safari/IOS Safari: Version 9.1/9.3 (Enabled by default).
Opera: Under development.
W3C SPEC
Full specification for upcoming css variables
Read Mome
Comments 3