Table of Contents
Use syntax
Perhaps surprising to newbies, the most common preprocessor limitation is that Sass cannot be used in media Define variables in the query or use @extend.
Since the ultimate purpose of CSS is to add styles to HTML, it turns out that there is another effective way to scope variables: DOM elements. But since the preprocessors don't run in the browser and can't see the markup, they can't do this.
预处理器变量不继承
预处理器变量不可互操作
Home Web Front-end CSS Tutorial Introduction to native variable var in CSS/CSS3

Introduction to native variable var in CSS/CSS3

Oct 26, 2017 am 09:33 AM
css css3

Use syntax

First let’s look at an example:
html code:


<p class="element">这是一段文字</p>
Copy after login

css code:


.element {
  width:200px;
  height:200px;
  --main-bg-color: #000;
  color:#fff;
  background-color: var(--main-bg-color);
}
Copy after login

Achievement effect:

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

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{
    --main-bg-color: #000;
}.element {
    background-color: var(--main-bg-color);
}
Copy after login

Note: Variable names cannot contain $, [, ^, (, % and other characters, Ordinary characters are limited to "numbers [0-9]" "letters [a-zA-Z] " "underline_" and "dash- " These combinations, but can be Chinese, Japanese or Korean, for example:


##

.element {
  width:200px;
  height:200px;
  --黑色: #000;
  color:#fff;
  background-color: var(--黑色);
}
Copy after login

Full syntax of css variables: The complete syntax used by CSS variables is:
var( [, ]? ), which in Chinese is: var( [, , that is, if we do not define a variable name, then the following value will be used as its The default attribute value. is as follows:

##

.element {
    background-color: var(--new-bg-color,#EE0000);
}
Copy after login

The result obtained is of course the background of the value of the following color

Let’s take a look at the variable name. What will happen if it is illegal? See the following example:

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

What is the background color of at this time?

A. transparent
  • B. 20px
  • C. #369
  • D. #cd0000
  • The answer is:

A. transparent CSS variable, it is found that the variable value is Illegal, for example, the background color above obviously cannot be 20px, then 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

Application of css variables in js

Look at the following example, html code:

<p id="jsDom">这是一段文字</p>
Copy after login

css code:

#jsDom {
    --my-varwidth: 200px;
    background-color: #000;
    color:#fff;
    width:var(--my-varwidth);
    height:200px;
}
Copy after login

js code:

##

var element = document.getElementById(&#39;jsDom&#39;);var curWidth = getComputedStyle(element).getPropertyValue("--my-varwidth");
console.log(curWidth); //200px//设置过后该DOM元素的宽度变为了300pxelement.style.setProperty("--my-varwidth", &#39;300px&#39;);
Copy after login

What if the style is written between lines? Then do the following:

html code:


<p id="jsDom" style="--my-varwidth:400px;width:var(--my-varwidth);">这是一段文字</p>
Copy after login

js code:


var element = document.getElementById(&#39;jsDom&#39;);var curWidth = element.style.getPropertyValue("--my-varwidth");
console.log(curWidth); //400px
Copy after login

Browser compatibility


The browser compatibility is as shown in the figure:

As of now, IE11 does not support this css variable.

Speaking of which, I feel that this css variable is also very powerful. So compared with the preprocessor, which one do you think is better? Let’s talk about the disadvantages of preprocessors.

Preprocessor disadvantages

Preprocessor variables are not real-time

Perhaps surprising to newbies, the most common preprocessor limitation is that Sass cannot be used in media Define variables in the query or use @extend.

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

The above code will compile to:


.Container { 
     padding: 1em;
 }
Copy after login

As can be seen from the above results, the media query block is discarded, Variable assignments are ignored.


Since there is no way to vary variables based on matching @media rules, the only option is to assign a unique variable to each media query and write each variation individually.

Preprocessor variables cannot be cascaded

Whenever variables are used, scope problems inevitably arise. Should this variable be set as a global variable? Should it be scoped to files or modules? Should it be restricted to blocks?

Since the ultimate purpose of CSS is to add styles to HTML, it turns out that there is another effective way to scope variables: DOM elements. But since the preprocessors don't run in the browser and can't see the markup, they can't do this.

Suppose there is a website. For users who prefer larger text, add the class

# to the

element. ##user-setting-large-text. When this class is set, larger $font-size variable assignments should be applied:

$font-size: 1em;
.user-setting-large-text {
    $font-size: 1.5em;
} body { 
    font-size: $font-size; 
}
Copy after login

但同样,就像上面的媒体块示例,Sass完全忽略了该变量的赋值,这意味着这是不可能发生的。编译后的代码如下:


body { 
    font-size: 1em;
}
Copy after login

预处理器变量不继承

虽然继承严格说来是级联的一部分,之所以把它单独分出来讲,是因为多次想调用这个特性却不得。

假设一种情况,要在DOM元素上基于其父元素应用的颜色而设置样式:


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

上面的代码并不是有效的Sass(或CSS),但你应该明白它想达到什么目的。

最后一句声明试图在

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 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
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
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

See all articles