Creating CSS Global Variables : Stylesheet theme management -
this question has answer here:
- how can define colors variables in css? 19 answers
is there way set global variables in css such as:
@color1 = #fff; @color2 = #b00; h1 { color:@color1; background:@color2; }
latest update: 26/05/2017
css variables (custom properties) have arrived!
another year browser. edge has joined mozilla , google supporting great feature.
preprocessor "not" required!
there lot of repetition in css. single color may used in several places.
for css declarations, possible declare higher in cascade , let css inheritance solve problem naturally.
for non-trivial projects, not possible. declaring variable on :root
pseudo-element, css author can halt instances of repetition using variable.
how works
set variable @ top of stylesheet:
css
create root class:
:root { }
create variable:
:root { --bgd: #333; }
add names variable followed value:
(names can string choose.)
:root { --red: #b00; --blue: #00b; --fullwidth: 100%; }
set variables anywhere in css document:
h1 { color: var(--red); } #mytext { color: var(--blue); width: var(--fullwidth); }
browser support / compatibility
firefox: version 31+ (enabled default)
(leading way usual.) more info mozilla
chrome: version 49+ (enabled default).
"this feature can enabled in chrome version 48 testing enabling experimental web platform feature. enter chrome://flags/
in chrome address bar access setting."
safari/ios safari: version 9.1/9.3 (enabled default).
opera: version 39+ (enabled default).
android: version 52+ (enabled default).
ie: it's never going happen.
edge: version 15+ (enabled default).
css custom properties landed in windows insider preview build 14986
w3c spec
full specification upcoming css variables
try out
a fiddle , snippet attached below testing:
(it work supported browsers.)
: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 see 4 square boxes variables working expected.</p> <div class="bx1">i should red text on grey background.</div> <div class="bx2">i should grey text on black background.</div> <div class="bx3">i should grey text on blue background.</div> <div class="bx4">i should grey text on red background.</div>
Comments
Post a Comment