What is a CSS variable? Learning CSS variables: Inheritance & scope of CSS variables

Source: Internet
Author: User
Tags css preprocessor

What CSS variables can do to help us

in some imperative programming languages, like Java, C + + or JavaScript, we are able to track certain states through variables. A variable is a symbol that is associated with a specific value, and the value of the variable can change over time.
In a declarative language like CSS, values that change over time do not exist, and there is no concept of a variable.
CSS introduces the concept of a hierarchical variable that can handle the challenges of maintainability in a relaxed way. This makes it possible to refer to a variable symbolically in the entire CSS tree

First, what is a CSS variable

There are currently two types of CSS variables:

Variable, which is a valid identifier and a valid value. Can be used in any place. Variables can be used using the Var () function. For example, VAR (--example-variable) returns the value corresponding to--example-variable
Custom properties. These properties use the special format of the-where as the name. For example,--example-variable:20px, even if a CSS declaration statement. It means assigning 20px to the--example-varibale variable.

II. Declaration of variables

Name of the variable

The variable declaration uses two conjunction lines--the variable, $color is the syntax of SASS, @color is the syntax for less, and is used to avoid conflicting CSS native variables--)

Note: Variable names are case sensitive, --header-color and --Header-Color are two different variables

How to declare

The way CSS variables are declared is very simple, as follows, a CSS variable named color is declared.

    • Write in the CSS file

    • Written in the Inline-style of the HTML tag

    • Use JS to give an element a declaration, method. Style.setproperty

body{  --color:red;} <body style= "--color:red;" ></body>document.getelementsbytagname (' body ') [0].style.setproperty ('--color ', ' Red ')

Types of variable values

If the value of a variable is a string, it can be spliced with other strings

--bar: ' Hello ';--foo:var (--bar) ' world '; body:after {  content: '--screen-category: ' var (--screen-category);}

If the value of a variable is numeric and cannot be used directly with numeric units, you must use the Calc () function to connect them

. foo {  --gap:20;  /* Invalid *  /Margin-top:var (--GAP) px;}. foo {  --gap:20;  Margin-top:calc (VAR (--gap) * 1px);}

If the value of a variable has units, it cannot be written as a string

/* Invalid */.foo {  --foo: ' 20px ';  Font-size:var (--foo);} /* Valid */.foo {  --foo:20px;  Font-size:var (--foo);

Note: Variable values can only be used as property values and cannot be used as property names

. foo {  --side:margin-top;  /* Invalid *  /var (--side): 20px;}

In the above code, the variable--side is used as the property name, which is invalid

Iii. Inheritance & scope of CSS variables

Custom properties also support inheritance. A custom property is not defined on an element, and the value of the custom property inherits its parent element

class= "One" >  <p class= "One" >    <p class= "three" >    </p>    <p class= "four" >    </p>  <p></p>

Define the following CSS:

. both {--test:10px;}. three {--test:2em;}

In this example, the result of Var (--test) is:

    • class= node for "both": 10px

    • class= node for "three": Element:2em

    • class= "four" corresponding node: 10px (inherited from its parent)

    • class= node for "one": Invalid value, which is the default value for which the property value is not overridden by a custom CSS variable

The top-level scope is: root

Iv. response Type

p {  --color: #7F583F;  --BG: #F7EFD2;}. Mediabox {  Color:var (--color);  Background:var (--BG);} @media screen and (min-width:768px) {  body {    --color:  #F7EFD2;    --BG: #7F583F;  }}

V. Different from the pre-processor

1, pre-processor variables are not real-time

$color: #7F583F, @media screen and (min-width:768px) {    $color: #F7EFD2;}. Mediabox {      background: $color;}

Compile results

. mediabox {  background: #7F583F;}

2, pre-processor can not limit scope

$zcolor: blue;. Ulbox {    $zcolor: red;} ul{    color: $zcolor;}

Compiled to

UL {  color:blue;}

3. Pre-processor variables are not interoperable

Native CSS custom properties can be used with any CSS preprocessor or plain CSS file

Six, JS operation variables

CSS variables can interact with JS

: root{  --testmargin:70px;}  read var root = getComputedStyle (document.documentelement), var cssVariable1 = Root.getpropertyvalue ('-- Testmargin '). Trim (); Console.log (CssVariable1); ' 70px '//write Document.documentElement.style.setProperty ('--testmargin ', ' 100px '); var cssVariable2 = Root.getpropertyvalue ('--testmargin '). Trim (); Console.log (cssVariable2);  ' 100px '//delete document.documentElement.style.removeProperty ('--testmargin '); var cssVariable3 = Root.getpropertyvalue ('--testmargin '). Trim (); Console.log (CSSVARIABLE3); ' 70px '

VII. Compatibility

Methods to detect whether a browser supports CSS custom properties

/*css*/@supports ((--a:0)) {/    * supported */} @supports (not (--a:0)) {/    * not supported */}//Jsif (window.css && window. Css.supports && window. Css.supports ('--a ', 0)} {    alert (' CSS properties is supported ');} else {    alert (' CSS properties is not supported ' );}

Summarize

Compared to traditional preprocessor variables such as less and SASS, the advantages of CSS variables are:

    • The dynamic nature of CSS variables can be changed while the page is running, while traditional preprocessor variables cannot be changed after compilation

    • CSS variables can be inherited, can be used in combination, have scope

    • With Javascript, it is easy to read/write from JS

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.