1. Project requirements

Due to the need to use a unified style for many old projects, the need to agree a good CSS variable file, each project can be introduced at any time but do not need to adapt to their own preprocessor. In this case, CSS native variables are the best choice, so that no matter using LESS or SASS can use the same global CSS variable configuration file, and for the less project that did not use global variable configuration before there is no need to install a new package for variable processing.

2. What are CSS3 native variables

In fact, it is the same as the variable in less, define the variable in the use of reference, for better management of CSS, feel CSS will have a function one day… The format for defining variables must start with — because the @ flags are already occupied by other preprocesses.

Look at compatibility, there is no problem if you don’t use IE.

CSS native variable definition syntax is: –*, use syntax is: var(–*), where * represents our variable name, here use English name, Chinese name I have tried there will be compatibility problems. The easiest way to use it is to define a color globally so that you can reference the variable in any CSS style.

:root{-main-color: # 008080;
}

body{
  backgroud-color: var(--main-color);
}
Copy the code

3. Engineering practice

I’m currently working with less and can painlessly introduce a CSS variable file, varables.css, where I define the various global variables I need to use.

:root{
  --main-color: #008080;
  --main-font-size: 16px;
}
Copy the code

Then import the CSS variable file in the entry app.vue:

<style lang="less">
@import './styles/variables.css'
</style>
Copy the code

You can then reference CSS variables in less or CSS of any component.

4. More tricks

At this point, my CSS variables requirements have been met, but this feature is really nice on closer inspection. It has many other benefits, most notably the ability to use it in combination with JS or reactive layouts, in some cases directly changing the value of CSS variables for dynamic style changes. Zhang Xinxu is referred to.

<div id="box">
    <img src="mm.jpg" style="border: 10px solid var(--color);">
</div>
Copy the code
box.style.setProperty('--color'.'#cd0000');
Copy the code