CSS
语言:
CSSSCSS
确定
$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);
}
}
}