Not familiar with CSS variables, these five examples can be seen!

Time:2021-10-8

Author: Daniel
Translator: front end Xiaozhi
Source: stackabuse

Dream, dry goods, wechat search[move to the world]Pay attention to this dish washing wisdom who is still washing dishes in the early morning.

This article GitHubhttps://github.com/qq449245884/xiaozhiIt has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

As web applications get bigger, CSS gets bigger, verbose, and messy. Using CSS variables in a good context can provide us with a mechanism for reusing and easily changing recurring CSS properties.

Before pure CSS supported variables, we had preprocessors like less and sass. However, they need to be compiled before use, thus (sometimes) adding an additional layer of complexity.

How to define and use CSS variables (also known as custom properties)

To declare a simple JS variable, it is very simple, as follows:

let myColor = "green";

To declare a CSS variable, you must add two horizontal lines before the variable name.

body {
    --english-green-color: #1B4D3E;
}

Now, in order to use the value of CSS variables, we can usevar(...)Function.

.my-green-component{
    background-color: var(--english-green-color);
}

The easiest way to manage CSS variables is to declare them in:rootIn a pseudo class. Since CSS variables follow the same rules as other CSS definitions, put them in:rootIt will ensure that all selectors have access to these variables.

:root{
    --english-green-color: #1B4D3E;
}

Browser support for CSS variables

Browser support for CSS variables is not bad at all. If viewCan I Use CSS VariablesYou will find that all mainstream browsers support CSS variables. Whether on a mobile device or PC.

Not familiar with CSS variables, these five examples can be seen!

Now, let’s look at the actual role of these CSS variables.

Example 1 – manage colors

One of the best choices to use CSS variables is the color of the design. Instead of copying and pasting the same colors over and over again, we just put them in variables.

If a damn product wants us to update a specific green shadow or set all buttons to red instead of blue, just change the value of the CSS variable. We do not need to search and replace all occurrences of this color.

Not familiar with CSS variables, these five examples can be seen!

Try it:https://codesandbox.io/s/8kky…

Example 2 – delete duplicate code

Usually we need to build different variants of some components. The same basic style, but with slightly different functions. Let’s take an example of using buttons with different colors.

.btn {
  border: 2px solid black;
  // more props here
}

.btn:hover {
  background: black;
  // more props here
}

.btn.red {
  border-color: red
}
.btn.red:hover {
  background: red
}

Use them like this:

<button class="btn">Hello</button>
<button class="btn red">Hello</button>

However, this will increase some code duplication. stay.redClass, we must set the border color and background to red. If you need to change the color one day, it will be very troublesome. You need to change it one by one. This problem can be easily solved through CSS variables.

.btn {
    border: 2px solid var(--color, black);
}
.btn:hover {
    background: var(--color, black);
}
.btn.red {
    --color: red
}

Not familiar with CSS variables, these five examples can be seen!

Try it:https://codesandbox.io/s/yp29…

Example 3 – make certain attributes easy to read

If we want to create shortcuts for more complex attribute values, CSS variables are very useful so that we don’t have to remember it.

CSS properties, such asbox-shadowtransformandfontOr other CSS rules with multiple parameters are good examples.

We can put the attribute in a variable so that we can reuse it in a more readable format.

//Main code
:root {
  --tiny-shadow: 4px 4px 2px 0 rgba(0, 0, 0, 0.8);
  --animate-right: translateX(20px);
}
li {
  box-shadow: var(--tiny-shadow);
}
li:hover {
  transform: var(--animate-right);
}

Try it:https://codesandbox.io/s/q3ww…

Not familiar with CSS variables, these five examples can be seen!

Example 4 – cascading variables

Standard cascading rules also apply to CSS variables. If a custom attribute is declared multiple times, the lowest definition in the CSS file will overwrite the definition above it.

The following example demonstrates how easy it is to dynamically manipulate attributes on user actions while keeping the code clear and concise.

//Main code
.orange-container {
  --main-text: 18px;
}
.orange-container:hover {
  --main-text: 22px;
}
.red-container:hover {
  --main-text: 26px;
}
.title {
  font-size: var(--title-text);
}
.content {
  font-size: var(--main-text);
}

.container:hover {
  --main-text: 18px;
}

Not familiar with CSS variables, these five examples can be seen!

Try it:https://codesandbox.io/s/xj0q…

Example 5 – Theme switching and CSS variables

One of the great advantages of CSS variables is their responsiveness. Once we update them, any properties with CSS variable values will also be updated. Therefore, you can create a theme switcher mechanism with just a few lines of JavaScript and clever use of CSS variables.

Not familiar with CSS variables, these five examples can be seen!

Try it:https://codesandbox.io/s/24j4…

extend

Like almost everything in CSS, variables are very simple and easy to use. Here are some tips that are not included in the examples, but are still useful in some cases:

Note that CSS variables are case sensitive

:root {
 --color: blue;
 --COLOR: red;
}
/*--color and --COLOR are two different variables*/

When we usevar()Function, you can also pass in a second parameter. If the custom attribute cannot be found, this value will be used:

width: var(--custom-width, 33%);

CSS variables can be used directly with HTML

<!--HTML-->
<html style="--size: 600px">
body {
  max-width: var(--size)
}

You can use CSS variables in other CSS variables:

--base-red-color: #f00;
--background-gradient: linear-gradient(to top, var(--base-red-color), #222);

CSS variables can be used as conditions through media queries. For example, the following code changes the value of padding according to the screen size:

:root {
    --padding: 15px 
}

@media screen and (min-width: 750px) {
    --padding: 30px
}

staycalc()CSS variables can also be used in functions.

--text-input-width: 5000px;
max-width: calc(var(--text-input-width) / 2);

CSS variables are not a panacea. They won’t solve all the problems we encounter in the CSS field. However, it can make our code more readable and maintainable.

Moreover, they greatly improve the convenience of making changes across large documents. Just set all constants in a single file, and we don’t have to skip thousands of lines of code when we just want to change variables.

~After that, I’m Xiaozhi. I went to spa. Remember to point out a praise to support the oil.


The bugs that may exist after code deployment cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful bug monitoring toolFundebug

Original text:http://www.js-craft.io/blog/1…

communication

Dream, dry goods, wechat search[move to the world]Pay attention to this dish washing wisdom who is still washing dishes in the early morning.

This article GitHubhttps://github.com/qq44924588…It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

Not familiar with CSS variables, these five examples can be seen!