Things you may not know about CSS variables!

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

This article will take you through CSS variables 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!

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

1. Be careful! important

and CSS Using variables together !important is a bit weird, as shown in the following demonstration:

p {
  --color:red !important;

  color:var(--color);
  color:blue;
}
Copy after login

What color will the p element above be? You would think it is red red, and think that it is executed as follows:

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

However, it is not red red, because the actual execution is like this:

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

In this case, !important is not part of color, but adds properties to the --color variable. Specification specifies:

Note: Custom attributes can contain !important, but they will be automatically deprecated by the CSS parser Delete in, This will change the custom attribute important into a hierarchy. In other words, it's not that !important doesn'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 the p element red color, and the analysis is as follows:

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

  • Then var(--color) will be applied red !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 that CSS variables (custom properties) should be treated as ordinary properties, not just variables that store values.

Custom attributes are common 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 @media and other conditional rules perform conditional processing, which can be used for the style attribute of HTML, which can be read and set using CSSDOM, 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 how url() is parsed. It's a bit tricky to parse, so I recommend you go to Stack Overflow Answer to find the answer. As you can see, we can easily fix this by assigning the entire url() 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

.box The element will have a red and blue gradient effect, right? Yet it is pure red. Well, I typed linear-* 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. 它们不可以存储 <span style="font-size: 18px;">inherit</span>

我们考虑下面的例子:

<div class="box">
  <div class="item"></div>
</div>
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

笔记:<declatation-value> 声明值必须代表一个标记,所以变量空值需要有一个空格。比如 --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
<div class="box">
  I will have `background:linear-gradient(blue,transparent) red;`
</div>
<div class="box" style="--color:green">
  I will have `background:linear-gradient(blue,transparent) green;`
</div>
<div class="box" style="--color: ;">
  I will have `background:linear-gradient(blue,transparent)  ;`
</div>
Copy after login
  • 第一个 box 没有定义变量,所以预设值被使用

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

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

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

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

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

很多人都想这么做:

:root {
  --p:5px;
  --p:calc(var(--p) + 1px); /* let&#39;s increment by 1px */
}
Copy after login
:root {
  --x: 5px;
  --y: 10px;
  /* let&#39;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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template