search
HomeWeb Front-endCSS TutorialIntroduction to the usage of variables in CSS (with examples)

This article brings you an introduction to the usage of variables in CSS (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. helped.

I saw Ruan Dashen’s article about using variables in CSS two days ago and sorted it out.

This important new CSS feature is already supported by all major browsers. This article provides a comprehensive introduction to how to use it, and you will find that native CSS becomes extremely powerful.

1. Declaration of variables

When declaring a variable, two hyphens must be added in front of the variable name (--) .

body {
  --foo: #7F583F;
  --bar: #F7EFD2;
}

In the above code, two variables are declared in the body selector: --foo and --bar.

They are no different from formal properties such as color and font-size, but they have no default meaning. Therefore, CSS variables are also called "CSS custom properties". Because variables and custom CSS properties are actually the same thing.

You may ask, why choose two conjunction lines (--) to represent variables? Because $foo is used by Sass, and @foo is used by Less. In order to avoid conflicts, the official CSS variables use two conjunction lines instead.

Various values ​​can be put into CSS variables.

:root{
  --main-color: #4d4e53;
  --main-bg: rgb(255, 255, 255);
  --logo-border-color: rebeccapurple;

  --header-height: 68px;
  --content-padding: 10px 20px;

  --base-line-height: 1.428571429;
  --transition-duration: .35s;
  --external-link: "external link";
  --margin-top: calc(2vh + 20px);
}

Variable names are case sensitive, --header-color and --Header-Color are two different variables.

2. var() function

var() function is used to read variables.

a {
  color: var(--foo);
  text-decoration-color: var(--bar);
}

var()The function can also use a second parameter to represent the default value of the variable. If the variable does not exist, this default value will be used.

color: var(--foo, #7F583F);

The second parameter does not handle internal commas or spaces, and is regarded as part of the parameter.

var(--font-stack, "Roboto", "Helvetica");
var(--pad, 10px 15px 20px);

var()The function can also be used in the declaration of variables.

:root {
  --primary-color: red;
  --logo-text: var(--primary-color);
}

Note that variable values ​​can only be used as attribute values, not attribute names.

.foo {
  --side: margin-top;
  /* 无效 */
  var(--side): 20px;
}

In the above code, the variable --side is used as the attribute name, which is invalid.

3. Type of variable value

If the variable value is a string, it can be concatenated with other strings.

--bar: 'hello';
--foo: var(--bar)' world';

Using this, you can debug (example).

body:after {
  content: '--screen-category : 'var(--screen-category);
}

If the variable value is a numerical value, it cannot be used directly with the numerical unit.

.foo {
  --gap: 20;
  /* 无效 */
  margin-top: var(--gap)px;
}

In the above code, the value and unit are written directly together, which is invalid. They must be connected using the calc() function.

.foo {
  --gap: 20;
  margin-top: calc(var(--gap) * 1px);
}

If the variable value has a unit, it cannot be written as a string.

/* 无效 */
.foo {
  --foo: '20px';
  font-size: var(--foo);
}

/* 有效 */
.foo {
  --foo: 20px;
  font-size: var(--foo);
}

4. Scope

The same CSS variable can be declared in multiple selectors. When reading, the statement with the highest priority takes effect. This is consistent with the CSS "cascade" rule.

Below is an example.

<style>
  :root { --color: blue; }
  p { --color: green; }
  #alert { --color: red; }
  * { color: var(--color); }</style><p>蓝色</p><p>绿色</p><p id="alert">红色</p>

In the above code, all three selectors declare the --color variable. When different elements read this variable, the rule with the highest priority will be used, so the colors of the three paragraphs of text are different.

This means that the scope of a variable is the effective scope of the selector in which it is located.

body {
  --foo: #7F583F;
}

.content {
  --bar: #F7EFD2;
}

In the above code, the scope of the variable --foo is the effective scope of the body selector, and the scope of --bar is the effective scope of the .content selector.

For this reason, global variables are usually placed inside the root element:root to ensure that any selector can read them.

:root {
  --main-color: #06c;
}

5. Responsive layout

CSS is dynamic, and any changes to the page will lead to changes in the rules adopted.

Using this feature, you can declare variables in the media command of the responsive layout, so that different screen widths have different variable values.

body {
  --primary: #7F583F;
  --secondary: #F7EFD2;
}

a {
  color: var(--primary);
  text-decoration-color: var(--secondary);
}

@media screen and (min-width: 768px) {
  body {
    --primary:  #F7EFD2;
    --secondary: #7F583F;
  }
}

6. Compatibility processing

For browsers that do not support CSS variables, you can use the following writing method.

a {
  color: #7F583F;
  color: var(--primary);
}

You can also use the @support command for detection.

@supports ( (--a: 0)) {
  /* supported */
}
@supports ( not (--a: 0)) {
  /* not supported */
}

7. JavaScript operation

JavaScript can also detect whether the browser supports CSS variables.

const isSupported =
  window.CSS &&
  window.CSS.supports &&
  window.CSS.supports(&#39;--a&#39;, 0);

if (isSupported) {
  /* supported */
} else {
  /* not supported */
}

The writing method of JavaScript operating CSS variables is as follows.

// 设置变量
document.body.style.setProperty(&#39;--primary&#39;, &#39;#7F583F&#39;);

// 读取变量
document.body.style.getPropertyValue(&#39;--primary&#39;).trim();
// &#39;#7F583F&#39;

// 删除变量
document.body.style.removeProperty(&#39;--primary&#39;);

This means that JavaScript can store arbitrary values ​​into stylesheets. The following is an example of listening to an event, and the event information is stored in a CSS variable.

const docStyle = document.documentElement.style;

document.addEventListener(&#39;mousemove&#39;, (e) => {
  docStyle.setProperty(&#39;--mouse-x&#39;, e.clientX);
  docStyle.setProperty(&#39;--mouse-y&#39;, e.clientY);
});

Information that is useless to CSS can also be put into CSS variables.

--foo: if(x > 5) this.width = 10;

In the above code, the value of --foo is an invalid statement in CSS, but it can be read by JavaScript. This means that you can write style settings in CSS variables and let JavaScript read them.

So, CSS variables provide a way for JavaScript to communicate with CSS.

The above is the detailed content of Introduction to the usage of variables in CSS (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
利用CSS怎么创建渐变色边框?5种方法分享利用CSS怎么创建渐变色边框?5种方法分享Oct 13, 2021 am 10:19 AM

利用CSS怎么创建渐变色边框?下面本篇文章给大家分享CSS实现渐变色边框的5种方法,希望对大家有所帮助!

css ul标签怎么去掉圆点css ul标签怎么去掉圆点Apr 25, 2022 pm 05:55 PM

在css中,可用list-style-type属性来去掉ul的圆点标记,语法为“ul{list-style-type:none}”;list-style-type属性可设置列表项标记的类型,当值为“none”可不定义标记,也可去除已有标记。

css与xml的区别是什么css与xml的区别是什么Apr 24, 2022 am 11:21 AM

区别是:css是层叠样式表单,是将样式信息与网页内容分离的一种标记语言,主要用来设计网页的样式,还可以对网页各元素进行格式化;xml是可扩展标记语言,是一种数据存储语言,用于使用简单的标记描述数据,将文档分成许多部件并对这些部件加以标识。

css3怎么实现鼠标隐藏效果css3怎么实现鼠标隐藏效果Apr 27, 2022 pm 05:20 PM

在css中,可以利用cursor属性实现鼠标隐藏效果,该属性用于定义鼠标指针放在一个元素边界范围内时所用的光标形状,当属性值设置为none时,就可以实现鼠标隐藏效果,语法为“元素{cursor:none}”。

css怎么实现英文小写转为大写css怎么实现英文小写转为大写Apr 25, 2022 pm 06:35 PM

转换方法:1、给英文元素添加“text-transform: uppercase;”样式,可将所有的英文字母都变成大写;2、给英文元素添加“text-transform:capitalize;”样式,可将英文文本中每个单词的首字母变为大写。

rtl在css是什么意思rtl在css是什么意思Apr 24, 2022 am 11:07 AM

在css中,rtl是“right-to-left”的缩写,是从右往左的意思,指的是内联内容从右往左依次排布,是direction属性的一个属性值;该属性规定了文本的方向和书写方向,语法为“元素{direction:rtl}”。

css怎么设置i不是斜体css怎么设置i不是斜体Apr 20, 2022 am 10:36 AM

在css中,可以利用“font-style”属性设置i元素不是斜体样式,该属性用于指定文本的字体样式,当属性值设置为“normal”时,会显示元素的标准字体样式,语法为“i元素{font-style:normal}”。

怎么设置rotate在css3的旋转中心点怎么设置rotate在css3的旋转中心点Apr 24, 2022 am 10:50 AM

在css3中,可以用“transform-origin”属性设置rotate的旋转中心点,该属性可更改转换元素的位置,第一个参数设置x轴的旋转位置,第二个参数设置y轴旋转位置,语法为“transform-origin:x轴位置 y轴位置”。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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