css variable description and tutorial

小云云
Release: 2017-11-17 17:31:46
Original
2347 people have browsed it

CSS is an indispensable language for our front-end development. Being able to use it well will make our development very efficient. There have always been no variables in CSS. To use CSS variables, just You can use precompilers such as SASS or LESS. In March of this year, Microsoft announced that the Edge browser would support CSS variables. 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. This article will let you learn some uses of css variables.

1. Declaration of variables

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

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

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);}
Copy after login

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

2. var() function

The var() function is used to read variables.

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

The var() 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);
Copy after login

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()函数还可以用在变量的声明。
:root {  --primary-color: red;  --logo-text: var(--primary-color);}
Copy after login

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

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

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 spliced ​​with other strings.

--bar: 'hello';--foo: var(--bar)' world';
Copy after login

Using this, you can debug (example).

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

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;}
Copy after login

In the above code, the value and unit are written directly together, which is invalid. You must use the calc() function to connect them.

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

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);}
Copy after login

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; }
  div { --color: green; }
  #alert { --color: red; }
  * { color: var(--color); }</style><p>蓝色</p><div>绿色</div><div id="alert">红色</div>
Copy after login

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;}
Copy after login

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;}
Copy after login

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;
  }}
Copy after login

6. Compatibility processing

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

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

You can also use the @support command for detection.

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

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 */}
Copy after login

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;);
Copy after login

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);});
Copy after login

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

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

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.

I believe you have already mastered a lot of knowledge about css variables. I hope this tutorial can help you at work.

Related tutorials:

New knowledge: CSS variable-variable

##The first CSS variable: currentColor_html/css_WEB-ITnose

CSS variable trial_html/css_WEB-ITnose

The above is the detailed content of css variable description and tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!