Introduction to the Var of native variables in CSS/CSS3

Source: Internet
Author: User
Tags css preprocessor

Using syntax

Let's first look at an example:
HTML code:


<p class= "Element" > This is a text </p>

CSS code:


. element {  width:200px;  height:200px;  --main-bg-color: #000;  Color: #fff;  Background-color:var (--main-bg-color);}

Implementation results:

The result is that the background of the DOM element becomes black.

The syntax for a variable definition that is native --* to CSS is: the variable var(--*) uses the * syntax:, which represents our variable name. About naming this thing, a variety of languages have some display, such as CSS selectors can not be the beginning of the number, JS variables are not direct values, but in CSS variables, these restrictions are not, for example:


: root{    --main-bg-color: #000;}. element {    Background-color:var (--main-bg-color);}

Note: Variable names cannot contain $,[,^,(,% equal characters, but normal characters 数字[0-9] are 字母[a-zA-Z] 下划线_ Limited to "" "" "" and " 短横线- "These combinations, but can be Chinese, Japanese or Korean, for example:


. element {  width:200px;  height:200px;  --Black: #000;  Color: #fff;  Background-color:var (--black);}

CSS variable full syntax:
The complete syntax used by CSS variables is var( [, ]? ) :, in Chinese, is var( <自定义属性名> [, <默认值 ]? ) :, that is, if we do not define a variable name, then we will use the following value as its default property value.
As follows:


. element {    Background-color:var (--new-bg-color, #EE0000);}

The resulting result is of course the background of the value of the back color.

Let's see what happens if the variable name is not valid, see the following example:


body {  --color:20px;  Background-color: #369;  Background-color:var (--color, #cd0000);}

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

    • A. Transparent

    • B. 20px

    • C. #369

    • D. #cd0000

The answer is:A. transparent
CSS variables, the result is found that the value of the variable is not legal, for example, the background color above can not be 20px, then use the default value of the background color, is also the default value instead, then, the above CSS is equivalent to:


body {    --color:20px;    Background-color: #369;    Background-color:transparent;}

The application of CSS variables in JS

Look at the following example, HTML code:


<p id= "Jsdom" > This is a text </p>

CSS code:


#jsDom {    --my-varwidth:200px;    Background-color: #000;    Color: #fff;    Width:var (--my-varwidth);    height:200px;}

JS Code:


var element = document.getElementById (' jsdom '); var curwidth = getComputedStyle (Element). GetPropertyValue ("-- My-varwidth "); Console.log (curwidth); After the 200px//is set, the width of the DOM element becomes 300pxelement.style.setproperty ("--my-varwidth", ' 300px ');

What if the style is written to the rows? Then do the following:
HTML code:


<p id= "Jsdom" style= "--my-varwidth:400px;width:var (--my-varwidth);" > This is a paragraph of text </p>

JS Code:


var element = document.getElementById (' jsdom '), var curwidth = Element.style.getPropertyValue ("--my-varwidth"); Console.log (Curwidth); 400px

Browser compatible

Browser-compatible:

The CSS variable is not supported at the current location IE11.

When it comes to feeling this CSS variable is also very powerful, then it compares with the preprocessor, which do you think is better? Here's a look at the advantages of the preprocessor.

Preprocessor disadvantage

Preprocessor variables are not real-time

Perhaps to the novice's surprise, the most common case of preprocessor limitations is that sass cannot define variables or use @extend in media queries.


$gutter: 1em; @media (min-width:30em) {     $gutter: 2em;}  . Container {      padding: $gutter;  }

The above code compiles to:


. Container {      padding:1em;}

As can be seen from the above results, the media query block is discarded and the variable assignment is ignored.

Since variables cannot be changed on the basis of matching @media rules, the only option is to assign a unique variable to each media query and write each variant individually.

Preprocessor variables cannot be cascaded

Whenever a variable is used, the scope problem inevitably arises. Should this variable be set to a global variable? Should the scope be limited to files or modules? Should the block be restricted?

Since the ultimate goal of CSS is to add styles to HTML, it turns out that there is another effective way to scope variables: DOM elements. However, they cannot do this because the preprocessor is not running in the browser and cannot see the markup.

Suppose you have a Web site that, in the face of a user who prefers larger user-setting-large-text text, adds a class to the element. When you set this class, you should apply a large $font-size variable assignment:


$font-size:1em;. User-setting-large-text {    $font-size:1.5em;} body {     font-size: $font-size;}

But again, like the media block example above, sass completely ignores the assignment of the variable, which means that this is not possible. The compiled code is as follows:


body {     font-size:1em;}

Preprocessor variable does not inherit

Although inheritance is strictly a part of the cascade, the reason for it to separate itself is that it is not possible to invoke this feature many times.

Suppose a situation is to set a style on a DOM element based on the color applied to its parent element:


. alert {    background-color:lightyellow;}. alert.info {    background-color:lightblue;}. alert.error {    background-color:orangered;}. Alert button {    border-color:darken (Background-color, 25%);}

The above code is not a valid sass (or CSS), but you should understand what it is trying to achieve.

The last sentence declares a function that attempts .alert to use Sass a darken property inherited from background-color A parent element element in the <button> element. If the info class error is already added .alert (or if background-color passed JavaScript or user style is set) , the button element can respond accordingly.

Obviously this Sass中行不通 is in, because 预处理器不知道DOM结构 , but hopefully you clearly realize why this kind of thing is useful.

Call a specific use case: for accessibility reasons, it is extremely convenient to run the color function on the inherited DOM property. For example, make sure the text is always readable and in sharp contrast to the background color. With custom attributes and a new CSS color function, this will soon be possible.

Preprocessor variables are not interoperable

This is a relatively obvious drawback of the preprocessor and refers to it because I think it is important. If you're using it PostCSS to build a website and want to use a third-party component that can only be themed with sass, you're out of luck.

It is not possible (or at least not easy) to share preprocessor variables on third-party style sheets that are hosted across different toolsets or CDNs.

Native CSS custom properties can be used with any CSS preprocessor or plain CSS file. Otherwise it is not.

Here's how to use a CSS variable in a media query:


: root {    --gutter:1.5em;} @media (min-width:30em) {    : root {        --gutter:2em;    }} @media (min-width:48em) {    : root {        --gutter:3em;    }}

If it is a preprocessor, it is not valid to write.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.