Home > Web Front-end > CSS Tutorial > Understanding CSS/CSS3 native variable var

Understanding CSS/CSS3 native variable var

巴扎黑
Release: 2017-04-29 13:48:51
Original
1850 people have browsed it

1. Variables are a good thing

In any language, the role of variables is the same, which is to reduce maintenance costs, along with the benefits of higher performance and higher file compression rate.

With the attention and increasing popularity of CSS precompilation tools Sass/Less/Stylus, the CSS working group quickly followed up on the specification of CSS variables, and many browsers have followed suit. Currently, they can be used directly in some projects.

Understanding CSS/CSS3 native variable var

Chrome/Firefox/Safari browsers are all green, and their compatibility far exceeded my expectations, so I decided to try them out and record the syntax usage and features.

2. CSS variable var() syntax, usage and characteristics

The native variable definition syntax in CSS is: --*, and the variable usage syntax is: var(--*), where * represents our variable name. Regarding naming, various languages ​​have some indications. For example, CSS selectors cannot start with a number, and variables in JS cannot be directly numerical. However, in CSS variables, these restrictions are not present, for example:

:root {
  --1: #369;
}
body {
  background-color: var(--1);
}
Copy after login

The result background color is as follows:

Understanding CSS/CSS3 native variable var

However, it cannot contain characters such as $, [, ^, (, %, etc. Ordinary characters are limited to "numbers [0-9]", "letters [a-zA-Z]", "underscore_" and "dash-" "These combinations, but can be Chinese, Japanese or Korean, for example:

body {
  --深蓝: #369;
  background-color: var(--深蓝);
}
Copy after login

Therefore, we can directly use the Chinese name as the variable. Even those who have not passed English Level 4 will not be stressed, and we do not need to keep a translator by our side at all times.

​Both the definition and use of variables can only be inside the declaration block {}. For example, the following is invalid:

--深蓝: #369;
body {
  background-color: var(--深蓝);
}
Copy after login

The definition or declaration of variables is similar to the declaration of CSS counters. You should get rid of the preconceived syntax influence of pre-compiled tool syntax such as Sass/Less and understand the native variables of CSS as a CSS property.

This way, the rules you apply to their weights and variables will be much easier to understand.

For example, the following example:

:root { --color: purple; }
p { --color: green; }
#alert { --color: red; }
* { color: var(--color); }

<p>我的紫色继承于根元素</p>
<p>我的绿色来自直接设置</p>
<p id=&#39;alert&#39;>
  ID选择器权重更高,因此阿拉是红色!
  <p>我也是红色,占了继承的光</p>
</p>
Copy after login

In the above example we can get this information:

  1. Variables also follow CSS selectors. If the selector where the variable is located does not overlap with the element using the variable, it will have no effect. For example, the variable defined by #alert can only be enjoyed by the element with the id of alert. If you want the variable to be used globally, you can set it on the :root selector;


  2. When there are multiple variables with the same name, the coverage rules of the variables are determined by the weight of the CSS selector, but there is no such usage of !important because it is not necessary. The original intention of !important is to get rid of JS style settings, but for variables The definition of has no such requirement.

Can CSS property names be variables?

Similar to the following:

body {
    --bc: background-color;    
    var(--bc): #369;
}
Copy after login

The answer is "no". If it can be supported, the compression of CSS will be incredible. It is estimated that all attributes will be reduced to 1~2 characters.

Does CSS variable support multiple declarations at the same time?

Similar to the following:

​…

Sorry, it’s not similar. It’s not supported grammatically.

CSS variables use complete syntax

The complete syntax used by CSS variables is: var(, in Chinese it is: var( [,

Meaning, if the variable we use is not defined (note, only if it is not defined), the subsequent value will be used as the attribute value of the element. For example:

.box {
  --1: #369;
}
body {
  background-color: var(--1, #cd0000);
}
Copy after login

Then the background color at this time is #cd0000:

Understanding CSS/CSS3 native variable var

Illegal default properties of CSS variables

Please look at the following example:

body {
  --color: 20px;
  background-color: #369;
  background-color: var(--color, #cd0000);
}
Copy after login

Excuse me, what is the background color of at this time?

A. transparent    B. 20px     C. #369      D. #cd0000
Copy after login

The answer is……………………A. transparent

I don’t know if you got the answer right!

This is a very interesting point about CSS variables. For CSS variables, as long as the syntax is correct, even if the value in the variable is a mess, it will be parsed as a normal declaration. If the variable value is found to be illegal, such as the background above The color obviously cannot be 20px, so the default value of the background color, which is the default value, is used instead. Therefore, the above CSS is equivalent to:

body {
--color: 20px;
background-color: #369;
background-color: transparent;
}
Copy after login

Never take it for granted that it is equivalent to background-color:20px, which is why it is emphasized above that the use of CSS default values ​​is limited to cases where the variables are undefined, and does not include illegal variables.

Space trailing characteristics of CSS variables

Please look at the following example:

body {
  --size: 20;   
  font-size: var(--size)px;
}
Copy after login

  请问,此时的font-size大小是多少?

  如果你以为是20px就太天真了,实际上,此处font-size:var(--size)px等同于font-size:20 px,注意,20后面有个空格,所以,这里的font-size使用的是元素默认的大小。因此,就不要妄图取消就使用一个数值来贯穿全场,还是使用稳妥的做法:

body {
  --size: 20px;   
  font-size: var(--size);
}
Copy after login

  或者使用CSS3 calc()计算:

body {
  --size: 20;   
  font-size: calc(var(--size) * 1px);
}
Copy after login

  此时,的font-size大小才是20px,

  CSS变量的相互传递特性

  就是说,我们在CSS变量定义的时候可以直接引入其他变量给自己使用,例如:

body {
  --green: #4CAF50;   
  --backgroundColor: var(--green);
}
Copy after login

  或者更复杂的使用CSS3 calc()计算,例如:

body {
  --columns: 4;
  --margins: calc(24px / var(--columns));
}
Copy after login

  对于复杂布局,CSS变量的这种相互传递和直接引用特性可以简化我们的代码和实现成本,尤其和动态布局在一起的时候,无论是CSS的响应式后者是JS驱动的布局变化。

  我们来看一个CSS变量与响应式布局的例子,您可以狠狠地点击这里:CSS变量与响应式布局实例demo

  默认进去是4栏,如下图:

默认进去demo UI 截图

  随着浏览器宽度减小,4栏可能就变成3栏,2栏甚至1栏,我们实际开发的时候,显然不仅仅是栏目数量变化,宽度小,往往意味着访问设备尺寸有限,此时我们往往会缩小空白间距以及文字字号大小,这样,有限屏幕才能显示更多内容。

  也就是说,当我们响应式变化的时候,改变的CSS属性值不是1个,而是3个或者更多,如果我们有3个响应点,是不是就至少需要9个CSS声明?但是,由于我们有了CSS变量,同时,CSS变量可以传递,当我们遭遇响应点的时候,我们只需要改变一个CSS属性值就可以了。

  下面就是本demo核心CSS代码(只需要改变--columns这一个变量即可):

.box {
    --columns: 4;
    --margins: calc(24px / var(--columns));
    --space: calc(4px * var(--columns));
    --fontSize: calc(20px - 4 / var(--columns));
}
@media screen and (max-width: 1200px) {
    .box {
        --columns: 3;
    }
}
@media screen and (max-width: 900px) {
    .box {
        --columns: 2;
    }
}
@media screen and (max-width: 600px) {
    .box {
        --columns: 1;
    }
}
Copy after login

  于是,我们在2栏下的效果就是这样,字号,间距随着栏目数量的减小也一并减小了,然后每栏之间间距是扩大了:

Understanding CSS/CSS3 native variable var

  有没有觉得CSS越来越屌了呢!哈哈~

  三、结束语

  由于目前几乎没有关于CSS3 var()的文章,因此,上面关于var()的语法特性等都是自己通过看规范文档,外加细致的测试得到的。但是,一个人的能力总是有限的,因此,必然还有很多var()变量有意思的点没发现,因此,就希望大家若是发现var()其他有意思的地方,欢迎评论告知,我们及时添加在文章中,方便你我他她它。

  多人合作项目我也会使用Less/Sass之类的预编译工具,但是,基本上用到的就是变量,其他高级功能,几乎都不怎么使用。所以,如果浏览器全方位支持了原生的CSS变量,我十有八九就会抛弃Less/Sass之类的工具。

The above is the detailed content of Understanding CSS/CSS3 native variable var. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.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