Things you may not know about CSS variables!

青灯夜游
Release: 2022-04-21 10:34:31
forward
2593 people have browsed it

This article will take you throughCSSvariables and introduce the things no one tells you about CSS variables. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Things you may not know about CSS variables!

CSSVariables are great, but do you know their details? [Recommended learning:css video tutorial]

1. Be careful! important

andCSSUsing variables together!importantis a bit weird, as shown in the following demonstration:

p { --color:red !important; color:var(--color); color:blue; }
Copy after login

What color will thepelement above be? You would think it isredred, and think that it is executed as follows:

p { color: red !important; color: blue; }
Copy after login

However, it is notredred, because the actual execution is like this:

p { color: red; color: blue; }
Copy after login

In this case,!importantis not part ofcolor, but adds properties to the--colorvariable.Specificationspecifies:

Note: Custom attributes can contain!important, but they will be automatically deprecated by theCSSparser Delete in,This will change the custom attribute important into a hierarchy. In other words, it's not that!importantdoesn't work, it's just ignored before syntax checking.

You will understand it easier with the following example:

p { --color: red !important; --color: blue; color: var(--color); }
Copy after login

The above code will give thepelement red color, and the analysis is as follows:

  • We have two declarations for the--colorattribute, so we need to solve itslevelproblem. The first definition has!important, so its level is relatively high

  • Thenvar(--color)will be appliedred !important

  • So we will getcolor: red

Let’s look at a piece of code again :

p{ --color: red !important; --color: blue; color:var(--color); color: pink;  }
Copy after login

According to the above logic, we will finally get the paragraph color of pinkpink.

A very important rule is thatCSS variables (custom properties) should be treated as ordinary properties, not just variablesthat store values.

Custom attributes arecommon attributes, so they can be defined on any element. They can be solved using the inheritance and cascading rules of common attributes. You can use@mediaand other conditional rules perform conditional processing, which can be used for thestyleattribute ofHTML, which can be read and set usingCSSDOM, etc.

#2. 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)); }
Copy after login

You should do this ✅

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

This restriction is related to howurl()is parsed. It's a bit tricky to parse, so I recommend you go toStack Overflow Answerto find the answer. As you can see, we can easily fix this by assigning the entireurl()to a variable.

3. They can make invalid values valid

This is also one of my favorite points, and also a troublesome point.

Let’s start with a basic case:

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

.boxThe element will have a red and blue gradient effect, right? Yet it is pure red. Well, I typedlinear-*wrong. I can easily spot this error because the browser crosses out the row and enables the background style of the previous row.

Things you may not know about CSS variables!

Now, let’s introduce the variables:

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

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

Things you may not know about CSS variables!

Why does this happen?

When we use variables as attributes, the browser will only evaluate the value at "compute value time" because we need to know the contents of the variable first. In this example, when the browser does the chaining, it will consider the attribute value to be valid, and then it will become invalid.

在我们的例子中,浏览器做级联时,认为最后一个声明是有效的。但是到评估值的时候,最后一个声明被认定是无效的,所以它被忽略。我们不会回头查看,因为我们在级联的时候已经处理过了,所以我们最后会得到一个透明的背景颜色。

你可能认为这种行为不符合逻辑的,但是它确符合逻辑。因为一个值是有效还是无效时基于CSS变量的,所以浏览器一开始时不能真正知道。

.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 ... */ }
Copy after login

如果一个属性包含一个或者更多的var()函数,而且这些函数都是语法有效的,必须假定整个属性的语法在解析时有效。当var()函数被替代后,在“计算值时间”才做语法检查。

简单来说:CSS变量将属性的状态作为一个后备,知道我们对其进行评估值。当评估值之后,我们可以说它是有效的或者无效的了。如果它是无效的,那么久太晚了,因为我们不会再回头使用上一个。

4. 它们可以不被使用单位

大多数的教材或课程都会展示下面的代码给你:

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

但是,你也可以这么做:

:root { --p: 10; } .box { padding: calc(var(--p)*1px); }
Copy after login

变量中拥有单位并不是强制的。

5. 他们可以动起来

最初,CSS变量被定义是没有动画属性的。

Animatable: no

但是,事情发生了变化,我们通过@property修饰,CSS变量可以做一些动画或者渐变。这个特性目前浏览器支持比较低,但是也是时候了解下了。

6. 它们不可以存储inherit

我们考虑下面的例子:

Copy after login
.box { border:2px solid red; } .item { --b:inherit; border:var(--b); }
Copy after login

直觉告诉我们,.item将会即成父元素的border,因为--b包含inherit,但是并不是。

正如我们在第1点上说到的,我们错误认为CSS变量会简单存储值,然后供我们往后使用,然而并不会。CSS变量(自定义的属性)是普通属性,所以inherit会被应用并不会存储值。

例子:

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

正如你所看到的,公共属性应用,逻辑上才可以继承inherit

上面的写法是鸡肋的,因为CSS变量默认是继承的。

7. 它们可以是空值

是的,你可以想下面这么做:

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

笔记:声明值必须代表一个标记,所以变量空值需要有一个空格。比如--foo: ;是有效的,var(--foo)将会返回一个空格。--foo:;是无效的。如下:

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

Things you may not know about CSS variables!

这个小技巧可以配合预设特性实现一些想不到的效果。

一个例子你就会明白这个技巧:

.box { background: linear-gradient(blue,transparent) var(--color,red); # 没有发现--color,取默认值 red }
Copy after login
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) ;`
Copy after login
  • 第一个box没有定义变量,所以预设值被使用

  • 第二个有定义的变量,所以它被使用

  • 最后一个设定了一个空的变量值,所以空值被使用。使用后就好比不需要var(--color, red)一样

空值允许我们移除属性中var()声明,在一个复杂的值中使用var()作用挺大。

8. CSS 变量不是 C++ 变量

很不幸的是,很多开发者趋向于比较CSS变量和其他语言的变量,然后在他们逻辑上有一大堆的问题。正是这个原因,我都不想叫他们变量而是自定义属性,因为他们确实是属性。

很多人都想这么做:

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

以上的示范都不能工作。第一个和第二个都有无效值,因为它们都有嵌套依赖。最后一个例子,paddingmargin都是20px,因为级联会获取第二个--s: 20px的变量去应用。

这很不幸,你应该停止用C++, Javascript, Java等语言的思维去思考CSS变量,因为它们有自己逻辑的自定义属性。

9. 它们只能从父元素传递给子元素

请记住这个黄金规则:CSS 变量总是从父元素(或者说祖先元素)传递给子元素,不会从子元素传递给父元素或兄弟元素

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

你可以会认为.box背景颜色是linear-gradient(green, blue)? 不,背景颜色会是linear-gradient(red, blue)

root元素是DOM元素的最上层,所以它是box的祖先元素,我们应用上面的黄金规则知道,子元素的--c1是跑不到linear-gradient(var(--c1),var(--c2)中的。

10. 它们可以有奇怪的语法

最后一个也是有趣的一个。

你知道你能像下面这样写么?

body { --:red; background:var(--); }
Copy after login

很神奇,对吧?是的,CSS变量可以仅使用两节虚线定义。

你会认为上面已经很疯狂了?看下下面这个:

body { --?:red; --?:green; --?:blue; --?:orange; }
Copy after login

是的,你还可以用表情来定义一个变量。

CSS变量允许你以--开头的任何内容。比如:

body { ---------:red; background:var(---------); }
Copy after login

又比如:

body { --‎:red; --‎:blue; background:linear-gradient(90deg, var(--‎),var(--‎)); }
Copy after login

其实上面是这样的:

Things you may not know about CSS variables!

当然你不会使用这么稀奇古怪的东西在你的实际项目中,除非你想让你的老板或合作开发者发疯

总结

不知不觉有很多的内容了,你不需要马上就记住所有的内容。我尽力将这些不为人知的CSS变量整理了出来。如果有一天你工作中需要这些知识点,你可以回头来看。

英文原文地址:https://dev.to/afif/what-no-one-told-you-about-css-variables-553o

本文是译文,采用意译。

(学习视频分享:web前端

The above is the detailed content of Things you may not know about CSS variables!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
css
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!