Table of Contents
Since then, there are no variables in CSS. To use CSS variables, you can only use precompilers such as SASS or LESS. With the release of the new draft, defining and using variables directly in CSS is no longer a fantasy. This article will introduce CSS variables in detail
CSS variables are entities defined by CSS authors that contain specific values ​​to be reused throughout the document. Use custom attributes to set variable names, and use specific var() to access
Like ordinary style attributes, variable attributes also support inheritance and cascading. In the following example, the variable value of the body element is green, and the variable value of the p element is red; based on the principle of cascading, the final background color of the p element is red
【 Combination】
CSS variables can interact with JS. It should be noted that you can only use the getPropertyValue() and setProperty() methods, but not the style attribute
One thing to note is that the variable is not supported!important
1. Maintainability
Home Web Front-end CSS Tutorial Analysis of CSS variables variable

Analysis of CSS variables variable

Jun 12, 2018 pm 03:25 PM

This article mainly introduces the analysis of CSS variables, which has certain reference value. Now I share it with everyone. Friends in need can refer to the previous words

Since then, there are no variables in CSS. To use CSS variables, you can only use precompilers such as SASS or LESS. With the release of the new draft, defining and using variables directly in CSS is no longer a fantasy. This article will introduce CSS variables in detail

Basic usage

CSS variables are entities defined by CSS authors that contain specific values ​​to be reused throughout the document. Use custom attributes to set variable names, and use specific var() to access

Compatibility: Mobile and IE browsers are not compatible

[Declaration of variables]

Variables must start with

--

. For example, --example-variable: 20px means assigning 20px to the --example-varibale variable. You can place the statement declaring the variable within any element. If you want to set a global variable, you can set it to: root, body or html

:root{
  --bgColor:#000;
}
Copy after login

The variable declaration is just like the ordinary style declaration statement. You can also use the inline style

<body style="--bgColor:#000">
Copy after login

The variable declaration statement must be included in an element and cannot be placed randomly.

//错误
<style>
--bgColor:#000;
</style>
Copy after login

【Use variables】

Use the var() function to use variables, and can be used anywhere. For example: var(--example-variable) will return the value corresponding to --example-variable

<body style="--bgColor:#000;">
    <p style="width: 100px;height: 100px;background-color: var(--bgColor)"></p>    </body>
Copy after login

The var() function also has an optional parameter, which is used to set the default value when the variable cannot obtain the value. When, the default value is used

<body>
    <p style="width: 100px;height: 100px;background-color: var(--bgColor,pink)"></p>    </body>
Copy after login

Inheritance and cascading

Like ordinary style attributes, variable attributes also support inheritance and cascading. In the following example, the variable value of the body element is green, and the variable value of the p element is red; based on the principle of cascading, the final background color of the p element is red

<body style="--bgColor:green;">
    <p style="width: 100px;height: 100px;--bgColor: red;background-color: var(--bgColor,pink)"></p>    </body>
Copy after login

Composition and calculation

【 Combination】

CSS variables can be used in combination

<style>.box{
    --top:20%;
    --left:30%;
    width: 100px;
    height: 100px;
    background-image: url(img/24/xiaoshu.jpg);
    background-position: var(--left)  var(--top);}</style><p class="box"></p>
Copy after login

However, CSS variables cannot be combined in the following forms. var(--color1)var(--color2) is not recognized by the browser. If separated, such as var(--color1) var(--color2), it will be parsed as #333 and cannot be recognized by the browser

<style>.box{
    --color1:#;
    --color2:333;
    width: 100px;
    height: 100px;
    background-color: var(--color1)var(--color2);}</style><p class="box"></p>
Copy after login

【Calculation】

Variables and ordinary styles The values ​​are the same. In addition to combination, you can also use calc for calculation

<style>.box{
    --borderWidth:2px;
    width: 100px;
    height: 100px;
    background-color:lightblue;
    border-left: calc(var(--borderWidth) * 2) solid black;}</style><p class="box"></p>
Copy after login

JS

CSS variables can interact with JS. It should be noted that you can only use the getPropertyValue() and setProperty() methods, but not the style attribute

[style attribute]

<p id="box" style="--color:lightgreen;background-color: var(--color)"></p>    <script>  var oBox = document.getElementById(&#39;box&#39;);
  console.log(oBox.style[&#39;--color&#39;]);    //undefined</script>
Copy after login

[getPropertyValue()]

<p id="box" style="--color:lightgreen;background-color: var(--color)"></p>    <script>  var oBox = document.getElementById(&#39;box&#39;);
  console.log(oBox.style.getPropertyValue(&#39;--color&#39;));//&#39;lightgreen&#39;</script>
Copy after login

【setProperty()】

<style>#box{    
    --color:lightgreen;
    background-color: var(--color);
    width: 100px;
    height: 100px;
    display:inline-block;}</style><button id="btn" type="button">变浅蓝</button><p id="box"></p>    <script>var oBox = document.getElementById(&#39;box&#39;);var oBtn = document.getElementById(&#39;btn&#39;);
oBtn.onclick = function(){
    oBox.style.setProperty(&#39;--color&#39;,&#39;lightblue&#39;);
}</script>
Copy after login

Not supported

One thing to note is that the variable is not supported!important

.box{
    --color:red;
    width: 100px;
    height: 100px;
    background-color:--color !important;
}</style><p class="box"></p>
Copy after login

The chrome browser screenshot is as follows

Purpose

1. Maintainability

Maintaining a color scheme or size scheme in a web page means that some styles are used multiple times in the CSS file appear and are reused. When modifying a plan, whether it is adjusting a certain style or completely modifying the entire plan, it will become a complex problem, and simple search and replacement is not enough. At this time, CSS variables come in handy

:root{
  --mainColor:#fc0;
}
.p1{
  color:var(--mainColor);
}
.p2{
  color:var(--mainColor);
}
Copy after login

2. Semantic

The second advantage of variables is that the name itself contains semantic information. CSS files become readable and understandable. main-text-color is easier to understand than #fc0 in the document, especially when the same color appears in different files

 3. More convenient implementation of @media media query

Generally, media queries are as follows

<style>.box{    
    width: 100px;
    height: 100px;
    padding: 20px;
    margin: 10px;
    background-color: red}@media screen and (max-width:600px) {
    .box{
        width: 50px;
        height: 50px;
        padding: 10px;
        margin: 5px;        
    }}</style><p class="box"></p>
Copy after login

However, if you use variables, you can streamline the code

<style>.box{    
    --base-size:10px;
    width: calc(var(--base-size) * 10);
    height: calc(var(--base-size) * 10);
    padding: calc(var(--base-size) * 2);
    margin: calc(var(--base-size) * 1);
    background-color: red;}@media screen and (max-width:600px) {
    .box{
        --base-size:5px;    
    }}</style><p class="box"></p>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's learning, more Please pay attention to the PHP Chinese website for related content!

Related recommendations:

Analysis of the positon attribute of CSS

How to set placeholder through css

The above is the detailed content of Analysis of CSS variables variable. 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

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)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles