📜 ⬆️ ⬇️

A quick guide to variables in CSS (reasons for usage, syntax and examples)



I have been experimenting with CSS variables for quite some time. If you have not yet approached them, you can use this brief guide to quickly navigate everything and get to work.

What it is?



Simple application example for buttons with scope

CSS variables allow you to define reusable values ​​in CSS.
')
They appeared quite a long time ago. Recently, they began to gain popularity due to broader browser support.

If you use a preprocessor, such as SASS, then you are already familiar with variables. Now you can do the same thing without a preprocessor.

Why use style variables?


Variables allow us to adhere to the DRY principle (don't repeat yourself). Thanks to them, we also have a way to create a single point of reference for duplicate values. If you use a preprocessor, then, most likely, the advantages of this approach are already familiar to you. Most often this is used to set the primary color that is used for a variety of elements.


Repeat background color for multiple selectors

In the fragment above, the value #e74c3c could and should be a variable. If we make a variable from this value, we will have a single point that can be referenced. This reduces the risk of bugs and problems with style, as it facilitates further maintenance.


Creating a reference point with a variable

In the second snippet, I use the preprocessor to show how you can use a variable for the background-color value.

Why not use preprocessor variables instead of native CSS variables?


Good question. In most cases, you will prefer to maintain the commitment to the preprocessor variables. This is true if you already use them. But you can take advantage of both approaches at once. This becomes relevant when the need arises to fully utilize the capabilities of native CSS variables. More on that later.

Native CSS variables should be used when:

  1. You do not have a preprocessor or you do not use it.
  2. You want to take advantage of native CSS variables.

The main advantages of native CSS variables


In my opinion, native CSS variables have two big advantages.

The first. They are updated at runtime! They can be managed using media queries, states, or even JavaScript. The browser will apply the changes. This opens up many possibilities.

In addition, CSS variables allow to take into account the scope. This means that you can change, say, the style or behavior of an element by updating the value of a variable. Otherwise, you have to prescribe new styles for this element from scratch. As a result, the amount of CSS at the output decreases.

Not the most beautiful syntax


Let's take an example.



What is the pseudo-selector :root ? Everything is logical: this is the pseudo-selector of the tree root. The selector :root can be used to define global variables. In this case, we define the rebeccapurple value for the variable --primary .



To define a variable, two hyphens are used as a prefix.



To use a variable, we need the function var .

And what happens when we refer to a variable whose value is not specified? In this case, reserve values ​​or default values ​​can be specified. The var function supports a second optional parameter, corresponding to backup values ​​or default values.



This fragment sets the source style for the button tag. Where possible, the value for --btn-color is applied to --btn-color . If the variable does not exist or the value is not specified, the value --primary .

There is no need to use a variable for our folbek. You can take the value. But with variables, it will be easier to maintain the code.

Note that no styles were declared for button.btn . Instead, the value is updated. Now it is appropriate to go to cascading and scopes.

Cascading and Scopes


When working with variables, cascading is taken into account, as well as the scope of variables. In the previous example, variables are declared in the pseudo-class :root . All variables in the selector :root have a global scope.

In one of the examples above, --primary was available to all selectors. Due to scope, this value can be redefined. For example, we need the value of --primary change for the premium class.



In this snippet, the value of the variable - --primary element of the premium class is dodgerblue . That is, if no class is applied to a button , the variable value is rebeccapurple . However, if you apply the premium class, the color will change to dodgerblue .

It is worth noting that, as is the case with inline styles, inline CSS variables have the highest priority.



In this fragment, the background color of the button will be red , despite the fact that the premium class is used here. This happens because the value of --primary described directly in the tag.

Value management


You can control the values ​​of CSS variables using other CSS rules. The main approaches are media queries and state changes.

For example, the value of a variable may change when the screen width exceeds a certain value.



The change will launch a browser redraw and show the result to the user.

In this case, the background gradient will change if the width exceeds 768px .

And how to manage variables using states? For example, take a button . The CSS variable will be updated based on the button state.



In this case, you can customize the style of the button based on the state :active .

Managing Values ​​with JavaScript


Managing variables from CSS is very convenient. But in order to truly gain control of them, you have to manage them with JavaScript. Fortunately, this is real.

The setProperty method allows setProperty to set and manage element style variables.



How to update a variable defined in a pseudo-class :root ? Good question. You will need to set the properties of the documentElement documentElement .



When you can manage CSS variables in this way, many possibilities open up. It is interesting to track the position of the cursor using the mousemove event.

Using calc () and dropping units


Try not to use units of measure in variables. This will facilitate further maintenance.



The calc() function allows you to normalize and set values ​​with the desired units of measurement.



CSS variables can even be used to store information about preferred units of measurement. In the fragment, for clarity, we took "1px", but you can replace it with "1pt", "1rem", etc.

The absence of units of measurement is usually more relevant when values ​​are set from JavaScript. When processing pure values, our script abstracts from CSS. Communication is broken.



When units of measurement are contained in CSS, service also passes through CSS.

Application examples


I am still learning various examples of using CSS variables. First of all, dynamic themeization comes to mind. Tracking the cursor and scrolling the screen are also interesting applications. I have prepared training materials that can be found below.

Example with a dog and a ball


Let's work one example together!



Here we just track the position of the cursor and update the position of the two emoji.



The main thing here is to move the emoji from the center point using the translate and at the same time apply the transition-delay for the dog.

How to update the position? Using variables for --x and --y .



How to make the dog behind? The transition-delay is applied. A difficult deceleration effect can also be achieved using the transition-timing-function .



All that remains is to update these variables for mousemove .



That's all. A couple of small improvements, and it turns out something like that:



disadvantages


So far, working with CSS variables has been going quite smoothly. I rarely have situations when something did not work. I will give a few possibilities that I would like to see for CSS variables.

  1. Animation of variables. In this article I didn’t talk about animation at all. You can use variables for it. But the animation of the values ​​themselves will not work.
  2. CSS variables cannot be used in selectors. This is logical, but it would be great if such an interpolation level would be available. Using variables in the nth-child selector would be cool.

Conclusion


I like working with CSS variables. The more I do them, the more applications come to mind.

Thanks to this article, you yourself can start learning CSS variables.

If you are interested in getting a more detailed overview of CSS variables, watch this video .


LOOKING.HOUSE - the project collected more than 150 points looking glass in 40 countries. You can quickly execute the host, ping, traceroute, and mtr commands.


Source: https://habr.com/ru/post/422487/


All Articles