Table of Contents
Why
Peel the cocoon and draw the silk
Define variables
Variable name
Inheritance and overriding of variables
Using variables
Compatibility and Inclusion
Just looking for a thorough explanation
Acknowledgments
Home Web Front-end HTML Tutorial CSS variable trial_html/css_WEB-ITnose

CSS variable trial_html/css_WEB-ITnose

Jun 24, 2016 am 11:49 AM

CSS is wonderful. It can put clothes on your page, all kinds of colorful clothes. However, for developers, it is not flexible enough, so there are all kinds of clothes. Such preprocessors include Sass, LESS, and Stylus (the author recommends Sass's SCSS syntax). These preprocessors can greatly improve the flexibility of CSS and enhance the code organization and maintenance of CSS. But after all, they are not biologically related. Then the experts in charge of CSS development couldn't sit still and began to give some new features to CSS. This article will discuss the progress and application of CSS variables.
W3C’s latest exploration of CSS variables is reflected in CSS Custom Properties for Cascading Variables Module Level 1. The latest update was on May 6, 2014. It is currently a working draft, so this article is only for research and exploration. There is a risk of modification to the knowledge points involved. This article will be updated simultaneously after W3C modifications.

Why

We know that a website or application often contains a large amount of CSS, and some attribute values ​​​​in these CSS are often reused, such as the color system used by the website, background color, text Color, link color, etc. These reused attribute values ​​are scattered in a large number of CSS documents. If you need to modify some of the values, such as changing the color, it is simply a nightmare. We need to find and replace each file, which is dizzying and mechanical. Repeated large-scale operations will inevitably lead to errors and headaches, so the organization and maintenance of CSS code has become an important bottleneck that plagues the use of CSS.
Of course, CSS preprocessing can effectively solve these problems. The use of preprocessors has become the de facto industry standard, and Sass is becoming the choice of more and more front-end ers. However, we need to deploy a compilation environment and enable development tools to support Sass, etc., which requires some additional work. When things happen, we can’t help but wonder, what if one day, we can use preprocessors like ordinary CSS?
So there is W3C’s CSS Various.

Peel the cocoon and draw the silk

About variables, it is nothing more than definition and use. Next, we will analyze them separately.

Define variables

We store the values ​​that need to be reused in a custom attribute. This custom attribute is marked with a double dotted line at the beginning, as shown in the following code.

/* 变量定义 */:root {  --main-color: #06c;}/* 变量使用 */#foo h1 {  color: var(--main-color);}
Copy after login

Variable name

Custom attribute names and variable names follow the definition rules of CSS identifiers and can contain alphanumeric (a-z, A-Z, 0-9), ISO 10646 character list U 00A0 and above characters, underscore (_), hyphen (-), etc., cannot start with numbers, hyphen numbers, or double hyphens.
CSS variable syntax is case-sensitive and can contain letters, numbers, underscores, and hyphens, and it is best not to start with numbers or hyphens.

/* 正确的变量名 */:root{	--link-color: #06c;	--_hover-color: #f6c;	--toolTip_color: #ff0;	--main_background_color: #333;}/* 下面两个变量都有效,表示两个变量 */:element{	--link-color:#06c;	--Link-color:#66c;}
Copy after login

The variable value can accept any value that conforms to the grammar. Its default value is " ", but it cannot be "", otherwise an error will be reported.

Inheritance and overriding of variables

The declaration and use of variables follow the cascading characteristics of CSS, similar to the variable scope in ordinary programming languages. Please look at the code below.

:root { --color: blue; }div { --color: green; }#alert { --color: red; }* { color: var(--color); }<p>I inherited blue from the root element!</p><div>I got green set directly on me!</div><div id='alert'>  While I got red set directly on me!  <p>I’m red too, because of inheritance!</p></div>
Copy after login

Using variables

We can use variables through var(), but we cannot use variables in attribute names and selectors. We can only use variables in attribute values. Use The syntax of the variable is as follows.

/*  * var()接受两个参数,自定义属性名(变量名)、缺省值 * 第一个参数custom-property-name调用变量 * 第二参数可选,指定自定义变量无效时的缺省值。 */var() = var( <custom-property-name> [, <any-value> ]? )/* for example *//* In the component’s style: */.component .header {  color: var(--header-color, blue);}.component .text {  color: var(--text-color, black);}/* In the larger application’s style: */.component {  --text-color: #080;  /* header-color isn’t set,     and so remains blue,     the fallback value */}
Copy after login

We can nested calls to CSS variables.

/*one example */:root {  --main-color: #c06;  --accent-background: linear-gradient(to top, var(--main-color), white);}/*another example */<one><two><three /></two></one>one   { --foo: 10px; }two   { --bar: calc(var(--foo) + 10px); }three { --foo: calc(var(--bar) + 10px); }
Copy after login

Compatibility and Inclusion

For front-end developers, compatibility and inclusion are always an unattainable pain. As a front-end er with a "geek mentality", we still have to work hard.
First of all, let’s take a look at the current appalling compatibility of CSS variables, as shown in the figure below, the data comes from caniuse.

The whole line is popular but only firefox knows it, so how can I play it?
What should I do if a brother says that I want to be willful and have fun? A foreigner wrote a patch (polyfill), you might as well give it a try.

Just looking for a thorough explanation

To sum up, CSS variables are in the draft stage and browser compatibility is average. I am writing this article today just to broaden my horizons and reserve knowledge. For commercial use, please use preprocessors such as Sass or LESS.
For more details, use the list below to learn more.

  • W3C reference
  • MDN info
  • caniuse
  • Acknowledgments

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

    Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

    HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

    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.

    What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

    AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

    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.

    Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

    GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

    How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? Apr 05, 2025 am 06:15 AM

    To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

    How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

    The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

    HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

    HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

    See all articles