h1 How to use css4 variables
small (custom properties)
|right now and maintain backwards compatibility.
div
button I'm a button
p Using the provided SASS var() function you can start using css4 custom properties and by changing the $css4 variable to 'false' it the function will return the value of the used variable instead of css4 function. So you can develope in css4 and in the end convert the whole styles back to css3.
p If you want to use css4 variables AND have fall-back to css3 in the same time, you can wrap the properties that use the var() function in the css4 mixin. This is the best way to use the css4 variables, as it can be easily maintained from css4 through css4 with css3 fallback, to css3 only, just by changing two variables - $css4, and $compatibility
h2 TRY IT YOURSELF! :)
small tip: try editing the variables in the html element from the inspector and see the real time changes without need of preprocessing time :)
View Compiled
$css4: true;
$compatibility: true;
//it is nessesary to define the variables in sass map instead of :root, for compatibility reasons.
$variables: (
--color: white,
--background: skyblue,
--font: sans-serif
);
//Here we transfer the variables from the map to the :root element
@if($css4) {
:root {
@each $variable, $value in $variables {
#{$variable}: $value;
}
}
}
//this is the "magic" function
@function var($variable) {
@if($css4) {
@return unquote('var(' + $variable + ')');
} @else {
@return map-get($variables, $variable);
}
}
//the mixin temporally sets the $css4 variable to false, compiles the css3 fallback, then makes the variable true again and compiles the css4 code. It should contain properties that use css4 variables, otherwise there will be unnessesary duplication of properties.
@mixin css4 {
@if ($css4) {
$css4-backup: $css4;
@if($compatibility) {
$css4: false !global;
@content;
}
$css4: true !global;
@content;
$css4: $css4-backup;
}
@else {
@content;
}
}
//the body does not use fallback, its styles will be visible only in compatible browsers
body {
max-width: 500px;
margin: 0 auto;
padding: 30px;
color: var(--color);
background: var(--background);
font: {
family: var(--font);
};
}
// the p and button tags uses the css4 mixin so a fall-back is provided and they will work on all browsers.
p {
text-align: justify;
@include css4 {
color: var(--color);
}
}
button {
@include css4 {
background: var(--color);
color: var(--background);
border: 2px solid currentcolor;
box-shadow: 0 0 0 5px var(--color);
};
&:hover {
@include css4 {
background: var(--background);
color: var(--color);
box-shadow: 0 0 0 5px var(--background);
}
}
}
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.