Photography |Eliott Reyna

I recently read an article called “Everything You Need to Know about CSS Variables” that gave me a new perspective on CSS Variables. The following will be sorted out with their feelings to share with you, I hope to help the CSS variables are still a little understanding of the students.

Answering questions

Why CSS variables are also called “custom properties”?

Let’s recall how CSS variables are used:

span {
    /* Local variable --color */
    --color: gold;
    color: var(--color);
}
Copy the code

CSS variables are declared in the same way as normal attributes, in the same place and in the same way.

CSS variables just have two more hyphens than normal properties — prefixes that are essentially properties. And this kind of attribute is created by the developers themselves, the attribute value is also set by us, naturally is “custom attribute”.

We can use var() to parse the values of these attributes:

color: var(--color);
/* is the same as */
color: gold;
Copy the code

Also, CSS variables, since they are attributes, can be used as inline styles:

<span style="--color: gold; color: var(--color);">The text is in gold</span>
Copy the code

The section “Manipulating CSS variables with JS” later in this article is based on this approach. We’ll talk about that later, but let’s move on.

Global variables and local variables

Global variables are declared like this:

:root {
    --color: gray;
}
Copy the code

The :root pseudo-class hits the document root element < HTML >

:root {
    --color: gray;
}
/* is the same as */
html {
    --color: gray;
}
Copy the code

The root element is the top-level element of the document, and variables declared below it are global variables. The corresponding variables are either global or local.

<style>
:root {
    /* Global variable --color */
    --color: gray;
}

p {
    /* Local variable --color */
    --color: gold;
    color: var(--color);
}
</style>This text is gray,<span>The text is in gold</span>
Copy the code

Similar to a JS scope, local variables override global variables of the same name. So the text in the above is gold.

Three,var()The parsed results can only be used as attribute values

It’s not ok to write:

.mt-20px { --mt: margin-top; var(--mt): 20px; /* * * * */Copy the code

We expected something like this: margin-top: 20px, but observed that the browser didn’t parse var(–mt) and said it was an unknown attribute name.

There is no problem with writing it like this:

.mt-20px {
    --20px: 20px;
    margin-top: var(--20px); /* √ 这样写就没问题了 */
}
Copy the code

Four,var()Fallback value of

The var() function, which also takes a second argument representing a fallback value that is used when the variable cannot be successfully parsed.

.header {
    color: var(--header-color, blue);
}
Copy the code

In the code above, if –header-color is not declared, the fallback value blue is used, somewhat like the default value for arguments in JS functions.

Fifth, usecalc()Do the math

If the declared variable value contains a mathematical operation, it is wrapped in the calc() function. Otherwise it’s an invalid operation.

Something like this is not correct:

.font-40px {
    --size: 20px * 2; /* * * * */
    font-size: var(--size);
}
Copy the code

When viewed in a browser, you will not see an explicit error, but the final parse value of font size is still the default 16px.

This type of error is not explicitly reported in the browser

The final parse value of ‘font-size’ is still ’16px’

You need to write:

.font-40px {
    --size: calc(20px * 2); /* √ */
    font-size: var(--size);
}
Copy the code

The introduction of the calc() function makes it much easier to do mixed numeric operations (addition, subtraction, multiplication, and division) in CSS with different units:

.example {
    /* 加 */
    width: calc(100% + 1em);
    /* 减 */
    width: calc(100% - 80px);
    /* 乘 */
    width: calc(100% * .5);
    /* 除 */
    width: calc(100% / 6);
}
Copy the code

See the documentation on the MDN for more details.

Use JS to manipulate CSS variables

JS manipulates CSS variables using the style property of a DOM object, which is an object of type CSSStyleDeclaration.

We might have done something like this before:

document.body.style.color = 'gold'
Copy the code

Color is a standard property and can be set directly in this way. CSS variables are nonstandard attributes and don’t work this way:

// * error because --color is not a standard attribute
document.body.style['--color'] = 'gold'
Copy the code

However, CSSStyleDeclaration provides a setProperty() method that can be used to set non-standard properties. The syntax is as follows:

style.setProperty(propertyName, value, priority);

So here’s what we can do:

document.body.style.setProperty('--color'.'gold');
Copy the code

The result is as follows:

In this way, we can manipulate CSS variables with JS.

practice

The use of CSS variables has changed the way we write and organize code. The idea is that we can change the value of an existing variable.

Here are two typical cases:

  1. Theme button
  2. Element’s transform transform

Theme button

We have four buttons with theme colors to use in different scenarios. In the previous form, this is done by overwriting attributes:

.btn {
    color: # 333;
    background-color: #eee;
    border: 0;
    padding:.5rem;
    cursor: pointer;
}

.btn-success {
    color: #fff;
    background-color: green;
}

.btn-error {
    color: #fff;
    background-color: red;
}

.btn-warning {
    background-color: orange;
}
Copy the code

If you use variables, you don’t need to override the attributes, just change the variable value.

.btn {
    color: var(--btn-color, #333);
    background-color: var(--btn-bg-color, #eee);
    border: 0;
    padding:.5rem;
}

.btn-success {
    --btn-color: #fff;
    --btn-bg-color: green;
}

.btn-error {
    --btn-color: #fff;
    --btn-bg-color: red;
}

.btn-warning {
    --btn-bg-color: orange;
}
Copy the code

IO /zhangbao/ PE…

Element’s transform transform

Take a look at the final image:

IO /zhangbao/ PE…

It works like this: when we drag the Range Input, we get the current value and set it to the value of the.color-boxes variable, which is used to set their Y offset.

The core code involved is as follows:

CSS:

.color-boxes {
    transform: perspective(500px) rotateY( calc(var(--slider) * 1deg));
}
Copy the code

JS

const range = document.querySelector('.booth-slider')

range.addEventListener('input', handleSlider)
function handleSlider (e) {
  document.documentElement.style.setProperty('--slider', e.target.value)
}
Copy the code

Well, it’s amazing.

The last

This article is my summary of knowledge points after reading a technical article, and added some of their own feelings. If I can help you after reading it, I will feel very honored! 😁

(after)