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

Understanding CSS/CSS3 native variable var

Apr 29, 2017 pm 01:48 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Apr 17, 2025 am 10:55 AM

In this week&#039;s roundup of platform news, Chrome introduces a new attribute for loading, accessibility specifications for web developers, and the BBC moves

The Deal with the Section Element The Deal with the Section Element Apr 12, 2025 am 11:39 AM

Two articles published the exact same day:

Multi-Thumb Sliders: General Case Multi-Thumb Sliders: General Case Apr 12, 2025 am 10:52 AM

The first part of this two-part series detailed how we can get a two-thumb slider. Now we&#039;ll look at a general multi-thumb case, but with a different and

Some Hands-On with the HTML Dialog Element Some Hands-On with the HTML Dialog Element Apr 16, 2025 am 11:33 AM

This is me looking at the HTML element for the first time. I&#039;ve been aware of it for a while, but haven&#039;t taken it for a spin yet. It has some pretty cool and

How We Tagged Google Fonts and Created goofonts.com How We Tagged Google Fonts and Created goofonts.com Apr 12, 2025 pm 12:02 PM

GooFonts is a side project signed by a developer-wife and a designer-husband, both of them big fans of typography. We’ve been tagging Google

It's All In the Head: Managing the Document Head of a React Powered Site With React Helmet It's All In the Head: Managing the Document Head of a React Powered Site With React Helmet Apr 15, 2025 am 11:01 AM

The document head might not be the most glamorous part of a website, but what goes into it is arguably just as important to the success of your website as its

See all articles