search
HomeWeb Front-endHTML TutorialCSS variable trial_html/css_WEB-ITnose

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

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

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>

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 */}

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

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
    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
    What is the purpose of HTML tags?What is the purpose of HTML tags?Apr 28, 2025 am 12:02 AM

    HTMLtagsareessentialforstructuringwebpages,enhancingaccessibility,SEO,andperformance.1)Theyareenclosedinanglebracketsandusedinpairstocreateahierarchicalstructure.2)SemantictagslikeandimproveuserexperienceandSEO.3)Creativetagslikeenabledynamicgraphics

    What are self-closing tags? Give an example.What are self-closing tags? Give an example.Apr 27, 2025 am 12:04 AM

    Self-closingtagsinHTMLandXMLaretagsthatclosethemselveswithoutneedingaseparateclosingtag,simplifyingmarkupstructureandenhancingcodingefficiency.1)TheyareessentialinXMLforelementswithoutcontent,ensuringwell-formeddocuments.2)InHTML5,usageisflexiblebutr

    Beyond HTML: Essential Technologies for Web DevelopmentBeyond HTML: Essential Technologies for Web DevelopmentApr 26, 2025 am 12:04 AM

    To build a website with powerful functions and good user experience, HTML alone is not enough. The following technology is also required: JavaScript gives web page dynamic and interactiveness, and real-time changes are achieved by operating DOM. CSS is responsible for the style and layout of the web page to improve aesthetics and user experience. Modern frameworks and libraries such as React, Vue.js and Angular improve development efficiency and code organization structure.

    What are boolean attributes in HTML? Give some examples.What are boolean attributes in HTML? Give some examples.Apr 25, 2025 am 12:01 AM

    Boolean attributes are special attributes in HTML that are activated without a value. 1. The Boolean attribute controls the behavior of the element by whether it exists or not, such as disabled disable the input box. 2.Their working principle is to change element behavior according to the existence of attributes when the browser parses. 3. The basic usage is to directly add attributes, and the advanced usage can be dynamically controlled through JavaScript. 4. Common mistakes are mistakenly thinking that values ​​need to be set, and the correct writing method should be concise. 5. The best practice is to keep the code concise and use Boolean properties reasonably to optimize web page performance and user experience.

    How can you validate your HTML code?How can you validate your HTML code?Apr 24, 2025 am 12:04 AM

    HTML code can be cleaner with online validators, integrated tools and automated processes. 1) Use W3CMarkupValidationService to verify HTML code online. 2) Install and configure HTMLHint extension in VisualStudioCode for real-time verification. 3) Use HTMLTidy to automatically verify and clean HTML files in the construction process.

    HTML vs. CSS and JavaScript: Comparing Web TechnologiesHTML vs. CSS and JavaScript: Comparing Web TechnologiesApr 23, 2025 am 12:05 AM

    HTML, CSS and JavaScript are the core technologies for building modern web pages: 1. HTML defines the web page structure, 2. CSS is responsible for the appearance of the web page, 3. JavaScript provides web page dynamics and interactivity, and they work together to create a website with a good user experience.

    HTML as a Markup Language: Its Function and PurposeHTML as a Markup Language: Its Function and PurposeApr 22, 2025 am 12:02 AM

    The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

    The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

    The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

    See all articles

    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

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor