Home Web Front-end CSS Tutorial What is the usage of CSS variable var()? Detailed explanation of the usage of CSS variable var()

What is the usage of CSS variable var()? Detailed explanation of the usage of CSS variable var()

Jan 21, 2019 pm 01:30 PM
css variables

When a web project gets bigger, its CSS can become astronomically large and cluttered. To help us solve this problem, new CSS variables will soon appear in major browsers, allowing developers to reuse and easily edit recurring CSS properties. Anyone who has used SASS or Less should know how great its variable function is, but these variables are preprocessors and need to be compiled before use. Now that variables are available in vanilla CSS, you can use them in your browser instantly! [Recommended reading: CSS Tutorial]

Defining and using CSS variables

Like any other CSS definition, variables follow the same scope and inheritance rules. The easiest way to use them is to make them globally available by adding the declaration to the :root pseudo-class so that all other selectors can inherit it.

html:

:root {
  --awesome-blue:#2196F3;
}
Copy after login

To access the value in a variable, we can use the var(…) syntax. Note that names are case-sensitive, so –foo != –FOO.

.element {
background-color:var(--awesome-blue);
}
Copy after login

Browser support

Commonly used browsers except IE are perfectly supported. You can get more details here – [I can use CSS variables](https://caniuse .com/#search=var()). Below are a few examples showing typical uses of CSS variables. To make sure they are working properly, try viewing them on one of the browsers we mentioned above.

Example 1 – Theme Colors

Variables in CSS are most useful when we need to apply the same rules over and over to multiple elements, such as repeating colors in a theme. Instead of copying and pasting every time we want to reuse the same color, we put it in a variable and access it from there.

Now, if our client doesn't like the shade of blue we choose, we can change the style in one place (the definition of the variable) to change the color of the entire theme. Without variables, we have to manually search and replace every occurrence.

You can copy the code and test it in your editor

* {margin: 0;padding: 0;box-sizing: border-box;}html {padding: 30px;font: normal 13px/1.5 sans-serif;color: #546567;background-color: var(--primary-color);}.container {background: #fff;padding: 20px;}h3 {padding-bottom: 10px;margin-bottom: 15px;}p {background-color: #fff;margin: 15px 0;}button {font-size: 13px;padding: 8px 12px;background-color: #fff;border-radius: 3px;box-shadow: none;text-transform: uppercase;font-weight: bold;cursor: pointer;opacity: 0.8;outline: 0;}button:hover {opacity: 1;}
<!-- 分割线 -->:root {
--primary-color: #B1D7DC;
--accent-color: #FF3F90;
}
html {
background-color: var(--primary-color);
}
h3 {
border-bottom: 2px solid var(--primary-color);
}
button {
color: var(--accent-color);
border: 1px solid var(--accent-color);
}
Copy after login
<div class="container">
<h3>对话框窗口</h3>
<p>过放荡不羁的生活,容易得像顺水推舟,但是要结识良朋益友,却难如登天。</p>
<button>确认</button>
</div>
Copy after login

Example 2 - Attribute class name readability

Another important use of variables is when we want to We don't have to remember it when we want to save more complex property values. The best example is having multiple parameters, such as the CSS rules box-shadow, transform and font.

By placing a property in a variable, we can access it using a semantically readable name.

html{background-color: #F9F9F9;}
ul{padding: 20px;list-style: none;width: 300px;}
li{font: normal 18px sans-serif;padding: 20px;transition: 0.4s;margin: 10px;color: #444;background-color: #fff;cursor: pointer;}
<!-- 分割线 -->
:root{
--tiny-shadow: 0 2px 1px 0 rgba(0, 0, 0, 0.2);
--animate-right: translateX(20px);
}
li{
box-shadow: var(--tiny-shadow);
}
li:hover{
transform: var(--animate-right);
}
Copy after login
<ul>
<li>我在这里!</li>
<li>我在这里!</li>
<li>我在这里!</li>
</ul>
Copy after login

Example 3 – Dynamically changing variables

Standard rules help resolve conflicts when a custom property is declared multiple times, and the last one defined in the stylesheet overrides the ones defined above.

The following example demonstrates how easy it is for users to dynamically change properties while still keeping the code clear and concise.

.container{background: #fff;padding: 20px;}
p{transition: 0.4s;}
.title{font-weight: bold;}
<!-- 分割线 -->
.blue-container{
--title-text: 18px;
--main-text: 14px;
}
.blue-container:hover{
--title-text: 24px;
--main-text: 16px;
}
.green-container:hover{
--title-text: 30px;
--main-text: 18px;
}
.title{
font-size: var(--title-text);
}
.content{
font-size: var(--main-text);
}
Copy after login
<div class="blue-container">
<div class="green-container">
<div class="container">
<p class="title">这是个标题</p>
<p class="content">将鼠标悬停在不同的颜色区域上可以更改此文本和标题的大小。</p>
</div>
</div>
</div>
Copy after login
[示例地址](https://codepen.io/w3cbest/pen/OrxLLE)
正如您所看到的,CSS变量非常简单易用,开发人员不必花费太多时间在各处开始应用它们。以下是扩展内容:
var()函数有两个参数,如果自定义属性失败,它可用于提供回退值:
Copy after login
width``: var(–custom-width, 20%``);
Copy after login

Custom attributes can be nested:

*   –base-color: #f93ce9;
*   –background-gradient: linear-gradient(to top, var(–base-color), #444);
Copy after login

Variables can be used in conjunction with another new feature of CSS - the calc() function.

*   –container-width: 1000px;
*   max-width: calc(var(–container-width) / 2);
Copy after login


The above is the detailed content of What is the usage of CSS variable var()? Detailed explanation of the usage of CSS variable var(). 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.

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:

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.

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?

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

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