Table of Contents
What CSS variables can help us do
1. What is a CSS variable
2. Variable declaration
Variable naming
Declaration method
Type of variable value
3. Inheritance & Scope of CSS Variables
4. Responsiveness
5. Differences from preprocessor
6. JS operation variables
7. Compatibility
Summary
Home Web Front-end CSS Tutorial What are CSS variables? Learning about CSS variables: Inheritance & scope of CSS variables

What are CSS variables? Learning about CSS variables: Inheritance & scope of CSS variables

Jul 30, 2018 pm 02:30 PM
css

What CSS variables can help us do

In some imperative programming languages, like Java, C or JavaScript, we can track certain states through variables. A variable is a symbol 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 variables.
CSS introduces the concept of hierarchical variables to easily cope with maintainability challenges. This will allow a variable to be symbolically referenced in the entire CSS tree

1. What is a CSS variable

CSS variables currently have two forms:

Variables , that is, having legal identifiers and legal values. Can be used anywhere. Variables can be used using the var() function. For example: var(--example-variable) will return the value corresponding to --example-variable
Custom attribute. These properties use the special format --where as their names. For example --example-variable: 20px; even a css declaration statement. It means assigning 20px to the --example-varibale variable

2. Variable declaration

Variable naming

The variable declaration uses two conjunction lines--to represent the variable, $color is a syntax that belongs to Sass, and @color is a syntax that belongs to Less. To avoid conflicts with css native variables, use --)

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

Declaration method

The CSS variable declaration method is very simple, as follows, a CSS named color is declared variable.

  • Write in the css file

  • Write in the inline-style of the html tag

  • Use JS to declare an element, method .style.setProperty

body{
  --color: red;
}
<body style="--color: red;"></body>
document.getElementsByTagName(&#39;body&#39;)[0].style.setProperty(&#39;--color&#39;, &#39;red&#39;)
Copy after login
Type of variable value

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

--bar: &#39;hello&#39;;
--foo: var(--bar)&#39; world&#39;;


body:after {
  content: &#39;--screen-category : &#39;var(--screen-category);
}
Copy after login

If the variable value is a numerical value, it cannot be used directly with the numerical unit. You must use the calc() function to connect them

.foo {
  --gap: 20;
  /* 无效 */
  margin-top: var(--gap)px;
}

.foo {
  --gap: 20;
  margin-top: calc(var(--gap) * 1px);
}
Copy after login

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

/* 无效 */
.foo {
  --foo: &#39;20px&#39;;
  font-size: var(--foo);
}

/* 有效 */
.foo {
  --foo: 20px;
  font-size: var(--foo);
Copy after login

Note: The variable value can only be used as the attribute value, not the attribute name

.foo {
  --side: margin-top;
  /* 无效 */
  var(--side): 20px;
}
Copy after login

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

3. Inheritance & Scope of CSS Variables

Custom properties also support inheritance. If there is no custom attribute defined on an element, the value of the custom attribute will be inherited from its parent element

class="one">
  <p class="two">
    <p class="three">
    </p>
    <p class="four">
    </p>
  <p>
</p>
Copy after login

Define the following CSS:

.two { --test: 10px; }
.three { --test: 2em; }
Copy after login

In this example, var(--test) The result is:

  • class="two" corresponding node: 10px

  • class="three" corresponding node: element: 2em

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

  • class="one" corresponding node: invalid value, that is, the value of this attribute is the default value that has not been overridden by the custom css variable

The top-level scope is: root

4. Responsiveness

p {
  --color: #7F583F;
  --bg: #F7EFD2;
}

.mediabox {
  color: var(--color);
  background: var(--bg);
}

@media screen and (min-width: 768px) {
  body {
    --color:  #F7EFD2;
    --bg: #7F583F;
  }
}
Copy after login

5. Differences from preprocessor

1. Preprocessor variables are not real-time

$color:#7F583F;

@media screen and (min-width: 768px) {
    $color: #F7EFD2;
}

.mediabox {
      background: $color;
}
Copy after login

Compilation results

.mediabox {
  background: #7F583F; 
}
Copy after login

2. Preprocessor cannot be limited Scope

$zcolor:blue;
.ulbox {
    $zcolor:red;
}
ul{
    color: $zcolor;
}
Copy after login

Compile to

ul {
  color: blue; 
}
Copy after login

3. Preprocessor variables are not interoperable

Native CSS custom properties can be used with any CSS preprocessor or pure CSS file Use together

6. JS operation variables

CSS variables can interact with JS

:root{
  --testMargin:70px;
}
//  读取
var root = getComputedStyle(document.documentElement);
var cssVariable1 = root.getPropertyValue(&#39;--testMargin&#39;).trim();
console.log(cssVariable1); // &#39;70px&#39;
 
// 写入
document.documentElement.style.setProperty(&#39;--testMargin&#39;, &#39;100px&#39;);
var cssVariable2 = root.getPropertyValue(&#39;--testMargin&#39;).trim();
console.log(cssVariable2);  // &#39;100px&#39;

// 删除
document.documentElement.style.removeProperty(&#39;--testMargin&#39;);
var cssVariable3 = root.getPropertyValue(&#39;--testMargin&#39;).trim();
console.log(cssVariable3); // &#39;70px&#39;
Copy after login

7. Compatibility

Check whether the browser supports CSS auto- Method of defining attributes

/*css*/

@supports ( (--a: 0)) {
    /* supported */
}

@supports ( not (--a: 0)) {
    /* not supported */
}
// Js

if (window.CSS && window.CSS.supports && window.CSS.supports(&#39;--a&#39;, 0)) {
    alert(&#39;CSS properties are supported&#39;);
} else {
    alert(&#39;CSS properties are NOT supported&#39;);
}
Copy after login

Summary

Compared with 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, used in combination, and have scope

  • Used with Javascript, you can easily read/write from JS

Related articles:

Learning of PHP- -Variable variables,--Variable variables

php Learning log-Variable scope, variables

Related videos:

Geek Academy CSS and CSS3 video tutorial

The above is the detailed content of What are CSS variables? Learning about CSS variables: Inheritance & scope of CSS variables. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

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.

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 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 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-

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.

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 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 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

See all articles