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

How to solve the problem of using CSS variable

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to solve the problem of the use of 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 "how to solve the problem of the use of CSS variables" bar!

1. Look out! important

Used with the CSS variable! important is a little weird, as shown in the following example:

P {- color:red! important; color:var (--color); color:blue;}

What color will the p element on it be? You will think it is red red, and think it will be executed according to the following code:

P {color: red! important; color: blue;}

However, it is not red red, because the actual implementation is as follows:

P {color: red; color: blue;}

In this case,! important is not part of color, but adds a feature of the-- color variable. It is specified in the specification:

Note: custom attributes can contain! important, but will be automatically removed from the properties by the CSS parser, which turns the custom attribute important into a hierarchy. In other words,! important is not ineffective, but is ignored before syntax checking.

The following example is easier for you to understand:

P {- color: red! important;-- color: blue; color: var (--color);}

The above code gives the p element red, which is parsed as follows:

We have declared the-- color attribute twice, so we need to address its hierarchy. The first definition comes with! important, so it has a relatively high level

Then var (--color) will apply red! important

So we get color: red.

Let's look at another piece of code:

P {--color: red! important;-- color: blue; color:var (--color); color: pink;}

According to the above logic, we end up with the paragraph color of the pink pink.

An important rule is that CSS variables (custom properties) should be treated as normal properties, not just variables that store values.

Custom attributes are ordinary attributes, so they can be defined on any element, can be solved using inheritance of ordinary attributes and hierarchical rules, can use @ media and other conditional rules for conditional processing, can be used for the style property of HTML, can be read and set using CSSDOM, and so on.

two。 They cannot store urls

One day you will stumble upon this common limitation.

You can't do this, ❌.

: root {--url: "https://picsum.photos/id/1/200/300";}.box {background:url (var (--url));}

You should do this, ✅.

: root {--url:url ("https://picsum.photos/id/1/200/300");}.box {background:var (--url);}

This restriction concerns how url () is parsed. It is a bit tricky to parse, so I recommend you to look for the answer on Stack Overflow Answer. As you can see, it's easy to fix it by assigning the entire url () to the variable.

3. They can make invalid values valid.

This is also one of my favorite points, but also a headache.

Let's start with a basic case:

.box {background: red; background: linaer-gradient (red, blue);}

The .box element will have a red and blue gradient effect, right? However, it is pure red. Well, I have the wrong number for linear-*. I can easily find this error because the browser crossed out this line and enabled the background style of the previous line.

Now, let's introduce variables:

.box {--color:red; background: var (--color); background: linaer-gradient (var (--color), blue);}

Test this code and you will find that the background color becomes transparent. Our second background color is not crossed out by the browser, but the first background style is crossed out. Because the second background style rewrites the first one.

Why did this happen?

When we use a variable as a property, the browser will only evaluate the value at the "calculation time", because we need to know the contents of the variable first. In such an example, when the browser does the cascading, the property value is considered to be valid and then becomes invalid.

In our example, when the browser makes a cascade, it thinks that the last declaration is valid. But by the time of the valuation, the last statement was found to be invalid, so it was ignored. We won't look back, because we've already dealt with it in the cascade, so we end up with a transparent background color.

You may think this behavior is illogical, but it is logical. Because the CSS variable is based on whether a value is valid or invalid, the browser doesn't really know at first.

.box {--color:10px; / * a "valid" variable * / background: red; / * a "valid" declaration * / background:linear-gradient (var (--color), blue); / * a "valid" declaration that will override the first one * / / * The result is an "invalid" value. * /}

If an attribute contains one or more var () functions, and these functions are syntactically valid, you must assume that the syntax of the entire attribute is valid at parsing. When the var () function is replaced, the syntax check is not done until the value time is calculated.

To put it simply: the CSS variable takes the state of the property as a backup until we evaluate it. After the evaluation, we can say that it is valid or invalid. If it doesn't work, it's too late, because we won't go back to the last one.

4. They can not be used in units.

Most textbooks or courses will show you the following code:

: root {- p: 10px;} .box {padding: var (--p);}

But you can also do this:

: root {- p: 10;}. Box {padding: calc (var (--p) * 1px);}

Owning a unit in a variable is not mandatory.

5. They can move.

Initially, CSS variables were defined as having no animation attributes.

Animatable: no

However, things have changed, and with @ property modification, the CSS variable can do some animation or gradients. This feature is currently poorly supported by browsers, but it's time to learn about it.

6. They cannot store inherit values

Let's consider the following example:

.box {border:2px solid red;}. Item {--bvir _ blank; border:var (--b);}

Intuition tells us that. Item will be the border of the parent element, because-- b contains inherit, but it is not.

As we said in point 1, we mistakenly assumed that the CSS variable would simply store the value and then use it later, but it would not. The CSS variable (custom attribute) is a normal property, so the inherit is applied and does not store the value.

Example:

.box {--b:5px solid blue; / * we define the variable on the parent * /}. Item {- bmistit; / * the child will inherit the same value so "5px solid blue" * / border:var (--b); / * we will have "5px solid blue" * /}

As you can see, the application of public properties can only logically inherit inherit.

The above is written in chicken ribs, because the CSS variable is inherited by default.

7. They can be null.

Yes, you can do this as follows:

.box {--color:; background:var (--color);}

Note: the declared value must represent a tag, so the null value of the variable needs to have a space. For example,-- foo:; is valid, and var (--foo) will return a space. -- foo:; is invalid. As follows:

.box {--color:; ❌ background:var (- color);}

This tip can be combined with preset features to achieve some unexpected effects.

As an example, you will understand this technique:

.box {background:linear-gradient (blue,transparent) var (--color,red); # not found-- color. Take the default value red} I will have `background:linear-gradient (blue,transparent) red; `I will have `background:linear-gradient (blue,transparent) green; `I will have `background:linear-gradient (blue,transparent); `

The first box does not define a variable, so the default value is used

The second variable has a definition, so it is used

The last one sets an empty variable value, so the null value is used. After using it, it is like not needing var (--color, red).

Null values allow us to remove the var () declaration from the attribute, and using var () in a complex value is very useful.

8. CSS variable is not C++ variable

Unfortunately, many developers tend to compare CSS variables with variables in other languages, and then have a lot of problems with their logic. For this reason, I don't want to call them variables but custom properties, because they are really properties.

A lot of people want to do this:

: root {--let's increment by 1px 5px;-- p:calc (var (--p) + 1px); / * let's increment by 1px * /}: root {--x: 5px;-- y: 10px; / * let's do a variable switch * /-- c: var (--y);-- y: var (--x);-- x: var (--c);} .box {--s: 10px; margin:var (--s) / * I want 10px of margin * /-s: 20px; padding:var (--s): / * then 20px of padding * /}

None of the above demonstrations will work. Both the first and the second have invalid values because they both have nested dependencies. In the final example, padding and margin are both 20px, because the cascading takes the second variable, s: 20px, to apply.

Unfortunately, you should stop thinking about CSS variables in languages such as Clippers, Javascript, Java, etc., because they have their own logical custom properties.

9. They can only be passed from parent elements to child elements.

Remember the golden rule: CSS variables are always passed from parent elements (or ancestral elements) to child elements, not from child elements to parent or sibling elements.

: root {--C1: red;-- c2: blue;-- grad: linear-gradient (var (--C1), var (--c2);} .box {--C1: green; background:var (--grad);}

Would you think the .box background color is linear-gradient (green, blue)? No, the background color will be linear-gradient (red, blue).

The root element is the top layer of the DOM element, so it is the ancestor element of box. We apply the golden rule above to know that the-C1 of the child element is not as good as that of linear-gradient (var (--C1), var (--c2).

10. They can have strange syntax.

The last one is also an interesting one.

Do you know you can write like this?

Body {- -: red; background:var (- -);}

It's amazing, right? Yes, the CSS variable can be defined using only two dotted lines.

You think it's crazy up there? Take a look at this:

Body {- -?: red;--?: green;--?: blue;--?: orange;}

Yes, you can also use facial expressions to define a variable.

The CSS variable allows you to start with-- anything. For example:

Body {: red; background:var (-);}

Another example is:

Body {--‎: red;-- ‎: blue; background:linear-gradient (90deg, var (--‎), var (--‎));}

In fact, it goes like this:

Of course you won't use such bizarre things in your actual project unless you want to drive your boss or co-developer crazy

Thank you for your reading, the above is the content of "how to solve the problem of the use of CSS variables". After the study of this article, I believe you have a deeper understanding of how to solve the problem of the use of 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