How to write variables in CSS? This article takes you to understand the front-end style tool

Table of contents

introduction

concept

grammar

basic usage

scenes to be used

global variable

local variable

​edit

media query variable

dynamic definition

inherit variable

independent variable

Differences from other programs

In the way of use

Scope difference

compiled product

Function and Expansion

Summarize

write at the end


introduction

The front-end variable writing methods can be roughly divided into three categories, namely CSS-in-JS, CSS preprocessor, and CSS native variables. As front-end developers, we should understand and make good use of them in order to achieve a more flexible and maintainable style. This article will share with you the variable writing method of native CSS

concept

CSS variables are also called custom attributes. Before it appeared, the values ​​​​used in CSS were usually hard-coded (statically written), which led to duplication and redundancy of style codes, and there were some troubles and hidden dangers in the management and maintenance of large projects.

To solve this problem, CSS variables were introduced into the CSS specification, enabling developers to declare and reuse customizable style properties. By defining and using variables, we can centrally manage styles, reduce code redundancy, and improve maintainability

grammar

In CSS, use the "--" prefix to define a variable, for example: --variable. Variables can be defined in the :root pseudo-class to achieve global scope, or they can be defined in specific selectors to limit the scope.

After the definition is complete, use the var() function to call the variable, and pass the variable name as a parameter, for example: var(--variable). Where variables need to be applied, use var(--variable) instead of a specific value or attribute value.

basic usage

The following is a global variable definition and usage example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <style>
      :root {
        --primary-color: lightblue;
        --primary-font: 20px;
      }
      .theme1 {
        width: 100px;
        height: 100px;
        background: var(--primary-color);
        font-size: var(--primary-font);
      }
    </style>
  </head>
  <body>
    <div class="theme1"></div>
  </body>
</html>

scenes to be used

global variable

Use the :root selector to select the root node. Combined with CSS variables, the variables can be defined globally. It has the highest priority, and all elements can access these variables. As in the example above

:root {
  --primary-color: lightblue;
}
.theme1 {
  background: var(--primary-color);
}

local variable

Local variables (also called block-level variables) are used in a wider range, and almost all selectors can declare variables. Here are a few examples

Define variable in class selector, use in child tags

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <style>
      .theme1 {
        --primary-color: lightblue;
      }
      .theme1 > span {
        color: var(--primary-color);
      }
    </style>
  </head>
  <body>
    <div class="theme1">
      <span>hello</span>
    </div>
  </body>
</html>

Set the theme attribute for html and use it in other tags. Here I implemented a simple theme switching function with the help of JS

<!DOCTYPE html>
<html theme="theme1">
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <style>
      [theme="theme1"] {
        --primary-color: lightblue;
        --primary-font-size: 20px;
      }
      [theme="theme2"] {
        --primary-color: lightcoral;
        --primary-font-size: 30px;
      }
      .theme > span {
        color: var(--primary-color);
        font-size: var(--primary-font-size);
      }
    </style>
  </head>
  <body>
    <button onclick="changeTheme()">切换主题</button>
    <div class="theme">
      <span>hello</span>
    </div>
    <script>
      const html = document.querySelector("html");
      function changeTheme() {
        if (html.getAttribute("theme") === "theme1")
          return html.setAttribute("theme", "theme2");
        html.setAttribute("theme", "theme1");
      }
    </script>
  </body>
</html>

The effect is as follows

media query variable

Under the condition of media query, we can also achieve the effect of dynamic update of styles by declaring CSS variables

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <style>
      @media (min-width: 300px) {
        :root {
          --primary-color: lightblue;
          --primary-font-size: 20px;
        }
      }
      @media (min-width: 600px) {
        :root {
          --primary-color: lightcoral;
          --primary-font-size: 30px;
        }
      }
      .theme > span {
        color: var(--primary-color);
        font-size: var(--primary-font-size);
      }
    </style>
  </head>
  <body>
    <div class="theme">
      <span>hello</span>
    </div>
  </body>
</html>

After running the above code, the effect is like this

dynamic definition

In addition, we can dynamically modify the variable value through element.setProperty, which is called dynamic definition, and the operation is as follows

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title></title>
    <style>
      :root {
        --primary-color: lightblue;
        --primary-font-size: 20px;
      }
      .theme > span {
        color: var(--primary-color);
        font-size: var(--primary-font-size);
      }
    </style>
  </head>
  <body>
    <button onclick="changeTheme()">切换主题</button>
    <div class="theme">
      <span>hello</span>
    </div>
    <script>
      const dom = document.documentElement;
      const { style } = dom;
      const colorKey = "--primary-color";
      function changeTheme() {
        const primaryColor = getComputedStyle(dom).getPropertyValue(colorKey);
        // 格式化后样式有空格
        if (primaryColor.includes("lightblue"))
          style.setProperty(colorKey, "lightcoral");
        else style.setProperty(colorKey, "lightblue");
      }
    </script>
  </body>
</html>

The function of getComputedStyle is to dynamically obtain the style object of the current label, getPropertyValue can obtain the custom properties of the label, and then use setProperty to set the custom properties

 

inherit variable

As mentioned above: the root root element declares variables, which are actually inherited when used in any child element. The variables defined by the parent tag can be accessed in descendant nodes

independent variable

And finally the arguments, tags defined in the same selector can be accessed within themselves

Differences from other programs

Knowing the above usage, what is the difference between CSS variables and preprocessors and CSS-in-JS?

In the way of use

CSS variables belong to the native syntax and can be used directly; the preprocessor needs a corresponding compiler; Css in Js is based on JS to embed CSS into JS development (generally commonly used in virtual Dom), and also requires corresponding dependencies.

Scope difference

CSS variables are defined in any selector, with the parent as the basic unit, and descendants have an inheritance relationship with it; CSS in JS is generally based on framework components, such as CSS Modules, styled-components; processors such as less and sass use component or file-level scope.

compiled product

CSS variables are calculated in real time; CSS in JS is compiled into CSS and embedded in HTML; preprocessors are compiled into CSS and used directly.

Function and Expansion

CSS variables can define simple variable expansion, or cooperate with CSS functions (calc, min, clamp, etc.) to perform calculations; CSS in JS can use complete JavaScript functions; preprocessors can not only have variable functions, but also use complex functions, such as importing, mixing, nesting, etc.

Summarize

CSS variables are suitable for defining reusable styles without using other dependencies, which is convenient and fast, but has few functions;

CSS in JS is suitable for componentized style management, has JS syntax support, requires installation dependencies, and has relatively powerful functions;

CSS preprocessor is used to expand CSS functions, and also needs to load dependencies, and its functions are relatively powerful

The three of them can complement each other and be used together

write at the end

This article mainly takes you to understand the concept and usage scenarios of CSS variables, and expands the difference between them and CSS-in-JS and CSS preprocessors. CSS variables are suitable for defining reusable styles and can deal with simple scenarios.

The above is the whole content of the article. I hope you have gained something after reading it. If you think the article is good, please support the author, thank you!

Guess you like

Origin blog.csdn.net/time_____/article/details/130666072