search
HomeWeb Front-endHTML TutorialDetailed explanation of variable usage in CSS_html/css_WEB-ITnose

Variables in CSS give us many advantages: convenience, code reuse, more reliable code base and improved error prevention capabilities.

Example

:root { --base-font-size: 16px; --link-color: #6495ed; }p { font-size: var( --base-font-size ); }a { font-size: var( --base-font-size ); color: var( --link-color ); }

Basics

There are three main components you should know when working with CSS variables:

  • Custom Properties
  • var() function
  • :root pseudo-class
  • Custom properties

    You already know some standard CSS properties, such as color, margin, width and font -size.
    The following example uses the CSS color property:

    body { color: #000000; /* The "color" CSS property */ }

    Custom properties simply means that we (the one who created the CSS file) define the name of the property.
    In order to customize an attribute name, we need to use -- as a prefix.
    If we want to create a custom property named text-color with a value of black, we can do this:

    :root { --text-color: #000000; /* A custom property named "text-color" */ }

    var() function

    In order to apply the customization Attributes need to use the var() function, otherwise the browser will not know what they represent.
    If you want to use --text-color in the styles in p, h1 and h2, you can use the var() function like this:

    :root { --text-color: #000000; }p { color: var( --text-color ); font-size: 16px; }h1 { color: var( --text-color ); font-size: 42px; }h2 { color: var( --text-color ); font-size: 36px; }

    It is equivalent to:

    p { color: #000000; font-size: 16px; }h1 { color: #000000; font-size: 42px; }h2 { color: #000000; font-size: 36px; }

    :root pseudo-class

    We need a place to put custom attributes. Although custom properties can be specified in any style rule, it is not a good idea to define properties everywhere, which is a challenge for CSS maintainability and readability.
    The :root pseudo-class represents the root element of an HTML document. This is a good place to put custom attributes because we can override custom attribute values ​​through other more specific selectors.

    Benefits of CSS variables

    Maintainability

    In a web development project, we often reuse a specific CSS property value:

    h1 { margin-bottom: 20px; font-size: 42px; line-height: 120%; color: gray; }p { margin-bottom: 20px; font-size: 18px; line-height: 120%; color: gray; }img { margin-bottom: 20px; border: 1px solid gray; }.callout { margin-bottom: 20px; border: 3px solid gray; border-radius: 5px; }

    The problem will be exposed when certain attribute values ​​need to be changed.
    If we change the property values ​​manually, especially when the CSS file is large, it will not only take a lot of time, but also may cause some errors. Likewise, if we perform a batched find and replace, we may inadvertently affect other style rules.
    We can use CSS variables to rewrite:

    :root { --base-bottom-margin: 20px; --base-line-height: 120%; --text-color: gray; }h1 { margin-bottom: var( --base-bottom-margin ); font-size: 42px; line-height: var( --base-line-height ); color: var( --text-color ); }p { margin-bottom: var( --base-bottom-margin ); font-size: 18px; line-height: var( --base-line-height ); color: var( --text-color ); }img { margin-bottom: var( --base-bottom-margin ); border: 1px solid gray; }.callout { margin-bottom: var( --base-bottom-margin ); border: 1px solid gray; border-radius: 5px; color: var( --text-color ); }

    Suppose your current customer says that the text color is too bright, making it difficult to read, and wants to change the text color. At this time, we only need to update one line CSS rules:

    --text-color: black;

    Improving the readability of CSS

    Custom attributes will make the style sheet more readable and make CSS property declarations more semantic.
    Compare this declaration

    background-color: yellow;font-size: 18px;

    with the following declaration

    background-color: var( --highlight-color );font-size: var( --base-font-size );

    Attribute values ​​like yellow and 18px don’t give us any useful contextual information, but When we read property names like --base-font-size and --highlight-color, we immediately know what the property value is doing, even in other people's code.

    Things to note

    Case sensitive

    Custom attributes are case sensitive (different from normal CSS rules)

    :root { --main-bg-color: green; --MAIN-BG-COLOR: RED; }.box { background-color: var( --main-bg-color ); /* green background */ }.circle { BACKGROUND-COLOR: VAR(--MAIN-BG-COLOR ); /* red background */ border-radius: 9999em; }.box,.circle { height: 100px; width: 100px; margin-top: 25px; box-sizing: padding-box; padding-top: 40px; text-align: center; }

    Parsing of custom attribute values

    When a custom attribute is repeatedly declared, its assignment follows the usual CSS cascading and inheritance rules. For example, the following example:
    HTML

    <body>  <div class="container">    <a href="">Link</a>  </div></body>

    CSS

    :root { --highlight-color: yellow; }body { --highlight-color: green; }.container { --highlight-color: red; }a { color: var( --highlight-color ); }

    When the .container rule is removed, the color value of the link will be green.

    Fallback value

    When using the var() function, you can assign a fallback attribute value as an extra parameter separated from the first parameter by,. Look at the following example:
    HTML

    <div class="box">A Box</div>

    CSS

    div { --container-bg-color: black; }.box { width: 100px; height: 100px; padding-top: 40px; box-sizing: padding-box; background-color: var( --container-bf-color, red ); color: white; text-align: center; }

    Because a fallback value parameter is passed to var(), the background color of the div is rendered. into red.

    Invalid value

    Beware of assigning the wrong type of value to a CSS property.
    In the following example, since the custom attribute --small-button is assigned a length unit, it is invalid when used in the .small-button style (Translator's Note: Because the color attribute type value is wrong)

    :root { --small-button: 200px; }.small-button { color: var(--small-button); }

    A good way to avoid this is to come up with descriptive custom property names. For example, name the above custom attribute --small-button-width

    Browser support for CSS variables

    CSS variables are very convenient to use, but the browser does not support it. Great:

    Or click this link: var supported

    This article is translated based on @Jacob Gube's "Introduction to CSS Variables". The entire translation contains my own understanding and thoughts. If translated If you don’t get it right or something is wrong, please ask your friends in the industry for advice. If you want to reprint this translation, please indicate the English source: http://sixrevisions.com/css/variables/.

    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
    HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

    HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

    HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

    HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

    From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

    HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

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

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

    The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

    The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

    HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

    HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

    HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 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.

    The Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesThe Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesApr 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.

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    EditPlus Chinese cracked version

    EditPlus Chinese cracked version

    Small size, syntax highlighting, does not support code prompt function

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    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.