Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the benefits of using CSS variables

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "what are the benefits of using CSS variables", the content of the explanation is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "what are the benefits of using CSS variables"!

What is the CSS variable?

If you have ever used a programming language, you are already familiar with the concept of variables. Variables are used to store and update the values your program needs to make it run.

For example, consider the following JavaScript code

Let number1 = 2 total number2 = 3 total total = number1 + number2;console.log (total); / / 5number1 = 4 x total = number1 + number2;console.log (total); / / 7

Nubmer1 and number2 are two variables that store the numbers 2 and 3, respectively.

Total is also a variable that stores the sum of number1 and number2. In this case, its value is 5. You can dynamically modify the values in variables and use them in the program. In the above code, I updated the value of number1 to 4 and then summed it. Using the same variable, the value stored in total is 5 instead of 7.

The beauty of using variables is that they allow you to store values in one place and update them later for a variety of reasons. In the program, you don't need to add additional characters to different values to indicate that any value updates take place in the same place. As in the variables you define.

CSS is largely a declarative language and lacks dynamic capabilities. You might think that letting CSS have variables almost contradicts the above statement. If front-end development is only about word games, it can be said that. Fortunately, Web programming languages are very much like languages in life, and they evolve and adapt to the needs of their surroundings and practices. The same is true of CSS.

Simply put, variables have become an exciting fact in the CSS world, and you will soon see for yourself that this amazing new technology is intuitive to learn and use.

What are the benefits of using CSS variables?

The benefits of using CSS variables are not much different from those of using variables in other programming languages.

This is how the specification describes this.

Use the CSS variable to add informative names to seemingly random values, making large files easier to read and edit with fewer errors. Because you only need to change the value once in the custom property, all places where this variable is applied will automatically change with it. W3C specification

In other words, by giving the variable a name that makes sense to you in the project, you can more easily manage and maintain your code. For example, when you set a variable name for the dominant tone in a project-primary-color, then when you modify the dominant tone later, you only need to change it in one place, rather than manually changing the value multiple times in multiple CSS files in different locations.

What is the difference between CSS variables and variables in preprocessors?

You may have tried the benefits of using variables in CSS preprocessors, such as Sass and Less.

Preprocessors allow you to set variables and use them in functions, loops, mathematical calculations, and so on. Does this mean that the CSS variable no longer matters?

That's not necessarily true, mainly because CSS variables are actually different from variables in preprocessors.

These differences are based on the fact that CSS variables are CSS attributes that are directly available in browsers, while variables in preprocessing are used to compile into regular CSS code, and the browser knows nothing about them.

This means that you can update the CSS variable directly in the stylesheet, in the inline style, in the SVG tag, or even modify it directly with JavaScript at run time. You can't do this with variables in the preprocessor. The CSS variable opens the door to a new world of possibilities.

This is not to say that you have to choose between the two: nothing limits you, you can use both CSS variables and preprocessing variables, and enjoy the huge benefits of each.

CSS variables: syntax

Although I use the term CSS variables (CSS variables) for the sake of brevity in this article, the official specification calls them CSS custom attributes (CSS custom properties for cascading variables) as cascading variables. The part of * CSS custom attribute (CSS custom property) * looks like this:

-- my-cool-background: # 73a4f4

Add a double-dash prefix to the custom attribute, and then set the value for the custom property as you would for a normal CSS. In the above code, I set a color value for a custom property called-- my-cool-backgroud.

The part of the cascading variable (cascading variable), which consists of using your custom properties through val (), looks like this:

Var (--my-cool-background)

The custom attribute acts in the CSS selector, and val () can be used as a real CSS property.

: root {--my-cool-background: # 73a4f4;}

/ * other parts of 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, which allows the custom attribute performance to be accessed globally (that is, anywhere inside the tag). Then, use the val () function to set the background-color of the container whose ID is foo to the value of the custom property, so that the container has a light blue background color.

It's not over. You can use the same light blue to set values for multiple HTML tags where you can set color values, such as setting their color and border-color. The method is simple: get the value of the custom property through var (--my-cool-background) and set it to 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, you can click to view.

You can also get the value of another CSS variable by using the CSS variable. For example:

-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 whose value is set to the result of a combination of-- top-color and-- bottom-color values. Now, you can change your gradient style at any time, just change the value of the variable, instead of having to fill the stylesheet to find the place where the gradient style is used.

Example 2 code.

Finally, you can add one or more alternate values (fallback value/s) to the CSS variable, such as:

Var (--main-color, # 333)

In the above code, # 333 is an alternate value. When the custom property value is invalid or unspecified (unset), if no alternate value is specified at this time, the inherited (inherited) property value will be used.

CSS variables are case sensitive

Unlike the normal CSS property, CSS variables are case-sensitive.

For example, var (--foo) and var (--FOO) are seeking two different custom attribute values, which are-- foo and-- FOO, respectively.

CSS variables are affected by cascading relationships

Like the normal CSS property, the CSS variable is inheritable. For example, we define a property with a value of blue:

: root {--main-color: blue;}

When you assign a main-color variable to any element in the tag, they inherit the value blue.

When you set a new value for changing a custom attribute in another element, all child elements of that element inherit that new value. For example:

: root {--main-color: blue;}. Alert {--main-color: red;} p {color: var (--main-color);}

The paragraph of blue

The paragraph of red

In the tag above, the first p paragraph inherits 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 the local scope-- main-color.

Example 3 code

It is almost enough to know that these rules are at present. Let's start writing code!

How to use CSS variables in SVG

The CSS variable works well with SVG. You can use the CSS variable to modify the styles in SVG, as well as the properties related to rendering.

For example, suppose you want your SVG icon to follow its parent container and have a different color. You can limit the scope of the CSS variable to the parent container, and then set the desired color to the variable, so that the icon inside will inherit the color value of the parent container. Here is the relevant code:

/ * inline SVG symbol for the icon * / x

/ * first instance of the icon * /

The above code uses tags, which allow you to create an invisible version of SVG graphics. Then use the tag to make a visible copy. This method allows you to create as many custom icons as you like, that is, to point to that through its ID (# close-icon). This is easier than writing repetitive code over and over again to create graphics. If you want to improve this convenient technique, Massimo Cassandro provides a quick tutorial in his Build Your Own SVG Icons.

Notice the stroke attribute in SVG symbol, the stroke attribute in the circle element, and the fill attribute in the text element: they both use the CSS variable, in this case-- 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 point, if you put the same SVG icon in a different parent container, and on the parent container, set their own local values for your CSS variables, then you will get different color icons and do not have to add extra rules to your stylesheet. This is cool!

To demonstrate this, we put the same icon in a div with the .success class:

Now, localize the-- icon-color variable, that is, put it in .success and set a green value. Let's take a look at what has changed:

/ * css * / .success {--icon-color: green;}

The color of this icon becomes green:

Let's look at a complete example: sample 4 code.

How to use CSS variables in @ keyframes

The CSS variable can be used in CSS animation, either for regular HTML elements or for inline SVG. Just remember, you need to know what element to move, treat it as the target element, then create a selector for that target element, define your CSS variables in the scope of the selector, and then use val () to get these variables and set them to the @ keyframes code block.

For example, let the elements in the .examples class in SVG move, and your CSS might look like this:

Animation {--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 the calc () of CSS and the var () function. They increase the flexibility of your code.

The simplicity of this example is that with the CSS attribute, you can simply modify the value of the variable in the corresponding selector to adjust the animation without having to look up the attributes in @ keyframes one by one.

Here is a complete example for you to experience: sample 5 code.

How to manipulate CSS variables through JavaScript

Another super cool thing is that you can access CSS variables directly from JavaScript code.

Suppose that in your CSS file, there is a variable called-- left-pos that acts in the .sidebar selector with the value 100px:

.sidebar {--left-pos: 100px;}

So, getting the-- left-pos value through JavaScript would look like this:

/ / cache the element const sidebarElement = document.querySelector ('.sidebar') that you are about to manipulate

/ / cached sidebarElement style 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 CSS variable to the console: 100pxconsole.log (cssVal)

If you want to set the value of the CSS variable through JavaScript, you can go 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.

Take a look at the following example in CodePen, where you can interactively click on the sidebar to modify the blend mode property and background color. These implementations use only the CSS variable 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 virtual query criteria (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 approach is feasible. If you use an alternate value in the val () function, your code will be more reliable and can be gracefully degraded in a browser with poor compatibility.

Thank you for your reading, the above is the content of "what are the benefits of using CSS variables", after the study of this article, I believe you have a deeper understanding of the benefits of using CSS variables, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report