This article translated from: www.sitepoint.com/practical-guide-css-variables-custom-properties/
Please specify the Source: Grape City website, Grape City for developers to provide professional development tools, solutions and services, empowering developers.
Sass and less such preprocessor, let our CSS code to maintain good structure and maintainability. Features like variables, blending (mixins), and loop control enhance the ability to dynamically write CSS, which reduces duplication of code and speeds up our development.
In recent years, some dynamic features have begun to appear in the CSS language as part of the specification. CSS variable (CSS variables), or with its official title, called Custom properties, is already available and has great browser support, and CSS mixins is making progress.
In this article, you'll learn how to use CSS variables and integrate it into your CSS development process to make your stylesheets more maintainable and less repetitive.
Let's get started now!
What is a CSS variable?
If you've ever used a programming language, you're already familiar with the concept of variables. Variables are used to store and update the values required by your program so that it runs.
For example, consider the following JavaScript code
let number1 = 2;
let number2 = 3;
let total = number1 + number2;
console.log (total); // 5
number1 = 4;
total = number1 + number2;
console.log (total); // 7
nubmer1 and number2 are two variables that store numbers 2 and 3, respectively.
total is also a variable, storing the sum of number1 and number2. Here its value is 5. You can dynamically modify the values in variables and use them in your program. In the above code, I updated the value of number1 to 4, and then summed. Using the same variable, the value stored in total at this time is 5, instead of 7.
The beauty of using variables is that it allows you to store the value in one place and allows you to update it later for various reasons. In the program, you don't need to add extra characters for different values: any value update occurs in the same place. Just like, on the variables you define.
CSS is largely a declarative language and lacks dynamic capabilities. You might think that letting CSS have variables almost makes the above statement contradict itself. If front-end development is only about word games, then so to speak. Fortunately, the programming languages of the Web are much like the languages in life. They will continue to evolve and adapt with the surrounding environment and practical needs. The same is true of CSS.
Simply put, variables have become exciting facts in the CSS world, and you are about to see for yourself that learning and using this powerful new technology is very intuitive.
What are the benefits of using CSS variables?
The benefits of using CSS variables are no different from the benefits of using variables in other programming languages.
The norm describes this
Use CSS variables to add seemingly random values to informative names, making large files easier to read and edit, and less error-prone. Because you only need to change the value once in the custom attribute, all the places where this variable is applied will automatically change with it. W3C specification
In other words, by giving the variable a meaningful name for you in the project, you can manage and maintain your code more easily. For example, when you set a variable name --primary-color for the main color in the project, then you only need to change one place when you modify this main color later, and you don't need to manually in multiple CSS files in different locations Modify the value multiple times.
What is the difference between CSS variables and variables in the preprocessor?
You may have tried the benefits of using variables in the CSS preprocessor, such as Sass and Less.
The preprocessor allows you to set variables and use them in functions, loops, mathematical calculations, and so on. Does this mean that CSS variables are irrelevant?
That's not necessarily because the CSS variables are actually different from the variables in the preprocessor.
These differences are based on the fact that CSS variables are CSS properties that are directly available in the browser, and the variables in the preprocessing are used to compile into regular CSS code, and the browser knows nothing about them.
This means that you can update CSS variables directly in SVG tags in style sheets, inline styles, or even modify it directly with JavaScript at runtime. And you can't do the above operations on the variables in the preprocessor. CSS variables opened the door to a new world full of possibilities.
It's not that you have to choose between the two: there is nothing restricting you, you can use CSS variables and preprocessed variables at the same time, and enjoy the huge benefits of each.
CSS variables: syntax
Although this article uses the term CSS variables for simplicity, the official specification calls them CSS custom properties for cascading variables as cascading variables. The part of * CSS custom property * looks like this:
--my-cool-background: # 73a4f4;
Add a double dash prefix in front of the custom attribute, and then set the value for the custom attribute as you would for ordinary CSS. In the above code, I set a color value for a custom property called --my-cool-backgroud.
And the cascading variable (cascading variable) part is composed of using your custom attributes through val (), and it looks like this:
var (-my-cool-background);
Custom attributes act on CSS selectors, and val () can be used as a real CSS attribute.
: root {
--my-cool-background: # 73a4f4;
}
/ * Other parts of the CSS file * /
#foo {
background-color: var (-my-cool-background);
}
The above code snippet defines the scope of the custom attribute --my-cool-background in the pseudo class root: this allows the custom attribute to be accessed globally (ie anywhere within the <html> tag ). Then, use the val () function to set the background-color of the container with ID foo to the value of the custom attribute, and then the container has a light blue background color.
This is not over yet. You can use the same light blue to set values for multiple places where multiple HTML tags can set color values, such as setting their color and border-color. The method is very simple, that is, get the value of the custom property through var (-my-cool-background), and then set the appropriate CSS property. (Of course, before things get complicated, I suggest thinking about your CSS variable naming convention):
p {
color: var (-my-cool-background);
}
Example 1 code, click to view.
You can also get the value of another CSS variable by using CSS variables. E.g:
--top-color: orange;
--bottom-color: yellow;
--my-gradient: linear-gradient (var (-top-color), var (-bottom-color));
The above code creates a --my-gradient variable, which is a gradient style, and its value is set to the result of the combination of the value of --top-color and the value of --bottom-color. Now, you can modify your gradient style at any time, just modify the value of the variable, and no longer need to find the place where this gradient style is used in the style sheet full of files.
Example 2 code.
Finally, you can add one or more fallback values / s to CSS variables, for example:
var (-main-color, # 333);
In the above code, # 333 is an alternate value. When the custom attribute value is invalid or unset, if no alternate value is specified at this time, the inherited attribute value will be used.
CSS variables are case sensitive
Unlike ordinary CSS properties, CSS variables are case sensitive.
For example, var (-foo) and var (-FOO) are seeking two different custom attribute values, namely --foo and --FOO.
CSS variables are affected by the cascading relationship
Like ordinary CSS properties, CSS variables are inheritable. For example, we defined an attribute with the value blue:
: root {
--main-color: blue;
}
When you specify the --main-color variable to any element in the <html> tag, they will inherit the value of blue.
When you set a new value for changing a custom attribute in another element, then all child elements of that element will inherit that new value. E.g:
: root {
--main-color: blue;
}
.alert {
--main-color: red;
}
p {
color: var (-main-color);
}
<-! HTML->
<html>
<head>
<!-head code here->
</ head>
<body>
<div>
<p> Blue paragraph </ p>
<div class = "alert">
<p> red paragraph </ p>
</ div>
</ div>
</ body>
</ html>
In the above tag, the first p paragraph will inherit the global --main-color value, which is blue.
The paragraph with the .alert class in the div tag will be red because its value inherits from --main-color in the local scope.
Example 3 code
Knowing that these rules are currently enough. Let's start writing code!
How to use CSS variables in SVG
CSS variables work well with SVG. You can use CSS variables to modify the styles in SVG and the attributes related to rendering.
For example, suppose you want your SVG icon to follow the parent container and have different colors. You can limit the scope of CSS variables in the parent container, and then set the variable to the desired color, then the icon inside will inherit the color value of the parent container. Here is the relevant code:
/ * inline SVG symbol for the icon * /
<svg>
<symbol id = "close-icon" viewbox = "0 0 200 200">
<circle cx = "96" cy = "96" r = "88" fill = "none" stroke = "var (-icon-color)" stroke-width = "15" />
<text x = "100" y = "160" fill = "var (-icon-color)" text-anchor = "middle" style = "font-size: 250px;"> x </ text>
</ symbol>
</ svg>
/ * first instance of the icon * /
<svg>
<use xlink: href = "# close-icon" />
</ svg>
The above code uses the <symbol> tag, which allows you to create an invisible version of the SVG graphic. Then use the <use> tag to generate a visible copy. This method allows you to create as many custom icons as you like, that is, point to that <symbol> by its ID (# close-icon). This is easier than writing repeated code over and over to create graphics. If you want to improve this convenient technique, Massimo Cassandro provides a quick tutorial in his Build Your Own SVG Icons.
Note that in the SVG symbol, the stroke attribute in the circle element and the fill attribute in the text element: both use CSS variables, here --icon-color It is defined in the selector of the: rootCSS file, like this:
: root {
--icon-color: black;
}
This is what the current icon looks like:
At this time, if you put the same SVG icon in a different parent container, and set the local values of your CSS variables on the parent container, then you will get icons of different colors, and do not need The style sheet adds extra rules. That's cool!
To show this, we put the same icon in a div with a .success class:
<!-html->
<div class = "success">
<svg>
<use xlink: href = "# close-icon" />
</ svg>
</ div>
Now, make the --icon-color variable localized, that is, put it in .success and set a green value. Let's take a look at the changes:
/ * css * /
.success {
--icon-color: green;
}
The color of this icon becomes green:
Let's take a look at a complete example: Example 4 code.
How to use CSS variables in @keyframes
CSS variables can be used in CSS animations, either for regular HTML elements or for inline SVG. Just remember, you have to know what element to move, think of it as the target element, then create a selector for the target element, define your CSS variables in the scope of the selector, and then use val () to get these Variables, set them into the @keyframes code block.
For example, by moving the <ellipse> element in the .bubble class in SVG, your CSS might look like this:
.bubble {
--direction-y: 30px;
--transparency: 0;
animation: bubbling 3s forwards infinite;
}
@keyframes bubbling {
0% {
transform: translatey (var (-direction-y));
opacity: var (-transparency);
}
40% {
opacity: calc (var (-transparency) + 0.2);
}
70% {
opacity: calc (var (-transparency) + 0.1);
}
100% {
opacity: var (-transparency);
}
}
Notice how this is calculated using CSS's calc () and using the var () function. They enhance the flexibility of your code.
The brevity of this example is that, using CSS properties, you can simply modify the value of the variable in the corresponding selector to adjust the animation without having to find the properties in @keyframes one by one.
Here is a complete example for you to experience: Example 5 code.
How to manipulate CSS variables through JavaScript
Another super cool thing is that you can access CSS variables directly through JavaScript code.
Suppose that in your CSS file, there is a variable called --left-pos, which acts in the .sidebar selector and has a value of 100px:
.sidebar {
--left-pos: 100px;
}
Then, getting the --left-pos value through JavaScript will look like this:
// Cache the element you are about to manipulate
const sidebarElement = document.querySelector ('. sidebar');
// Cache the style of sidebarElement in cssStyles
const cssStyles = getComputedStyle (sidebarElement);
// Get the value of the --left-pos CSS variable
const cssVal = String (cssStyles.getPropertyValue ('-left-pos')). trim ();
// Print the value of the CSS variable to the console: 100px
console.log (cssVal);
If you want to set the value of a CSS variable through JavaScript, you can do it like this:
sidebarElement.style.setProperty ('-left-pos', '200px');
The above code sets the value of the --left-pos variable in the sidebar element to 200px.
Please take a look at the following example in CodePen. You can interactively click on the sidebar to modify the blend mode property and background color. These implementations only use CSS variables and JavaScript.
Example 6 code.
Browser support for CSS variables
With the exception of IE11 (which does not support CSS variables), all major browsers have full support for CSS variables.
For browsers that do not support CSS variables, a workaround is to use @supports code blocks with dummy conditional query:
section {
color: gray;
}
@supports (-css: variables) {
section {
--my-color: blue;
color: var (-my-color, 'blue');
}
}
Considering that @supports also works in IE / Edge, the above method is feasible. If you use alternate values in the val () function, your code will be more reliable, and it can gracefully degrade in browsers with poor compatibility.
For the above code, in Chrome and other browsers that support CSS variables, the text in the <section> tag will be blue:
In IE11, since it does not support CSS variables, the page will display gray text:
You can view the example 7 code online.
One disadvantage of this method is that if you use a lot of CSS variables, and those browsers that do not support CSS variables have a high adaptation priority in your project, the corresponding code will become very complicated Say, even a nightmare.
In this case, you can choose to use PostCSS with cssnext, which allows you to use the latest features in the CSS code, and allows browsers that do not support these attributes to run these codes (a bit like JavaScript conversion What the device does).
Remarks: Here you can download all the codes listed in this article.