Introduction to the

How to make CSS like JS have variables to store attribute values, in the development of rapid reuse should have a variety of schemes, similar to less, SASS and other preprocessors. So CSS now supports its own variables. I learned a lot about the big boys

Declaration of variables

When declaring a variable, the variable name is preceded by two conjunction lines –.

:root {
    --color:# 000;
    --Color:# 001;

}Copy the code

The :root pseudoclass can be thought of as a global scope in which variables declared are available to all selectors below it

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

Use custom properties to set variable names and use a specific var() to access them, case sensitive

var(–color); var(–Color); They’re two different things

They are no different from formal attributes like color and font size, except that they do not have a default meaning. So CSS variables are also called “CSS Custom properties “. Variables and custom CSS properties are the same thing.

The var() function can also take a second argument that represents the default value of the variable. If the variable does not exist, the default value is used.

Var (–bg, #111) only exists if there is no default value

In fact, each curly brace is a scope, with inner precedence over outer variable precedence

:root {
    --color:# 000;

}
body {
    --color:# 002;color : var(--color); < span style> :root {--color: blue; } div { --color: green; }#alert { --color: red; }* { color: var(--color); </style> <p> blue </p> <div> green </div> <div id="alert"> red < / div >Copy the code

Note that CSS variables are not supported! Important statement.

The var() function can also be used to declare variables.

:root {
  --color: red;
  --bg: var(--color);
}Copy the code

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

:root {
  --color: color;
  var(--color): red;
}Copy the code

It’s not legal

The type of a variable value

  • If the variable value is a string, it can be concatenated with other strings.
    --one: '1px';
    --border: var(--one)' solid red';Copy the code
  • If the variable value is a numeric value, it cannot be used directly with a numeric unit.
    .foo { --top: 20; */ margin-top: var(--top)px; }Copy the code
  • If a variable value has a unit, it cannot be written as a string.
    .foo {
      --top: "20px"; */ margin-top: var(--top); margin-top: var(--top); }Copy the code
  • Values and units are written directly together and can be usedcalc()Function to connect them, but be careful for compatibility issues.
    .foo {
      --top: 20;
      margin-top: calc(var(--top) * 1px);
    }Copy the code

In the traditional CSS concept, the validity of attributes does not apply to custom attributes. When custom attributes are parsed, the browser does not know where to call them, so almost all values are valid. Unfortunately, these valid values can be called by the var() function operator, even if they don’t make sense at the moment. So properties and custom values can result in invalid CSS declarations.

  1. You cannot use CSS custom properties as CSS property names: var(–side): 10px;
  2. @media screen and (min-width: var(–min-width) {}
  3. Image addresses, such as URLS (var(–image-url)), do not take effect

Responsive layout

  • In general, when using media queries, we need to relist all the properties that will be changed in response. Using CSS variables, you can declare variables in the media command of a responsive layout, so that different screen widths have different variable values. Here it will be better than LESS and SASS
:root { --mainWidth:1000px; --leftMargin:100px; } .main { width: var(--mainWidth); margin-left: var(--leftMargin); } @media screen and (min-width:1480px) { :root { --mainWidth:800px; --leftMargin:50px; }}Copy the code

Compatibility processing

  • Don’t deal with it and abandon the lower version browser, too.
  • Check compatibility: To be honest, I don’t want to check compatibility by myself. Since it is the latest thing, the compatibility problem won’t be too serious when the team decides to use it
a {
  color: #7F583F;color: var(--primary); } /* Invalid declaration with attribute value */ @supports ((-)-a: 0)) {
  /* supported */
}
@supports ( not (--a: 0)) {/* not supported */} /* You can also use the @support command. */ const isSupported = window.CSS && window.CSS.supports && window.CSS.supports('--a', 0);

if (isSupported) {
    /* supported */
} else{/* not supported */} /* JavaScript checks whether the browser supports CSS variables. * /Copy the code

JavaScript operations

  • This is where CSS variables come in handy
  • Read and write attribute
:root{ --testMargin:75px; } var root = getComputedStyle(document.documentElement); Var cssVariable = root.getPropertyValue('--testMargin').trim();
console.log(cssVariable); // '75px'/ / write root. SetProperty ('--testMargin'.'100px'); // Remove variable root.removeProperty('--testMargin');Copy the code

This means that JavaScript can store arbitrary values into a stylesheet.

  1. Click the button to change the CSS variable value
const btn = document.getElementById("button");
const docStyle = document.documentElement.style;
btn.onClick = function(){
    docStyle.style.setProperty('--tplColor'.'yellow');
}Copy the code
  1. Listen for events, and the event information is stored in CSS variables.
const docStyle = document.documentElement.style;

document.addEventListener('mousemove', (e) => {
    docStyle.setProperty('--mouse-x', e.clientX);
    docStyle.setProperty('--mouse-y', e.clientY);
});Copy the code

The problem solved is practical

  1. Maintaining a color scheme means that some colors appear multiple times in a CSS file and are reused. When you modify a color scheme, it can be a complex problem to adjust one color or completely change the whole color scheme.
  2. The second advantage of these variables is that the name itself contains semantic information. CSS files become easy to read and understand. Main-text-color is easier to understand than #00ff00 in a document, especially if the same color appears in different files.
  3. Reduce the use of tools in the development process, reduce the cost of learning, ability greatly improved, no need for additional compilation.
  4. CSS variables are dynamic and can be changed at runtime, whereas traditional preprocessor variables cannot be changed after compilation
  5. CSS variables can be inherited, combined, and scoped
  6. With Javascript, it is convenient to read/write from JS and directly connect JS and CSS

CSS is actually a really cool thing and it’s really fun to make use of its properties, and it’s slowly becoming programmable.