From today on, WE will introduce CSS tips, the length is not long, you can read the time to pee, strive for a day, this is the first article.

  • What are CSS variables?
  • How to use it?

What are CSS variables?

CSS variables (officially called CSS custom properties), similar to variables in other languages, allow you to name a specified value for reuse in CSS. Custom property symbols usually start with “–“, (e.g. –my-color: black;) –color: var(–my-color); . Custom attributes play an important role in sharing styles between different elements and components (such as vertical rhythm, Typography variables, color palettes, etc.).

How to use CSS variables?

Thematic requirements such as dark mode are one of the most common examples of CSS variables. In such a requirement scenario, we can set CSS variables to control the hue, theme, and class to a common top-level element (such as a element or a top-level container).

The following example shows the inheritance of the child elements of a CSS global variable:

/* Global variables are defined in the :root element. */
:root {
  --bg-color: #fff;
  --main-color: #000;
  --secondary-color: #222;
}
/* Elements inherit variables from their parents. */
body {
  background-color: var(--bg-color);
  color: var(--main-color);
}
small {
  color: var(--secondary-color);
}
/* Elements can define their own values and variables, overriding inherited ones.*/
body.dark {
  --bg-color: #080808;
  --main-color: #fff;
  --secondary-color: #ccc;
}Copy the code

One useful aspect of custom variables is that we can define shared styles for different representations of an element, rather than having to copy styles over and over again. Here’s an example:

.btn {
  --bg-color: #002299;
  --text-color: #fff;
  --highlight-color: #669900;
​
  background-color: var(--bg-color);
  color: var(--text-color);
}
/* --highlight-color is also available to the children of .btn */
.btn .highlight {
  color: var(--highlight-color);
}
/* .btn.danger .highlight will use the --highlight-color defined in .btn-danger */
.btn-danger {
  --bg-color: #dd4a68;
  --text-color: #000;
  --highlight-color: #990055;
}Copy the code

Finally, keep the following tips for handling CSS variables in mind and use them wisely:

  • The var() function can set the callback value with a second argument (var(–text-color, black)); When the –text-color variable is not defined, the default is black.

  • CSS variables are case-sensitive and can be written inline like any OTHER HTML style (e.g.

    ).
  • CSS variables can be nested, such as calling other variables as callback(var(–main-color, var(–other-color)), or passing in other functions such as calc(), Even assigning var() to another variable (var(–main-color, var(–other-color))).

This article is published by OpenWrite, a blogging tool platform