📜 ⬆️ ⬇️

CSS Variables

If you are a developer, then you are familiar with variables, and perhaps they are some of your best friends. By definition, a variable is a temporary repository that contains some value or information.
But how does this relate to the CSS that we all know? A year ago on Habré was a post about planned innovations in CSS, which were announced by a member of the CSS working group and the Google Chrome team. Among these innovations was the introduction of support variables.
And so, just the other day, there were news about the release of the first release of the CSS Variable Desktop Draft (CSS Variables) .




Why are CSS variables?


Variables in CSS - this is the thing that people have been asking and wanting for quite a while .
Think of all these colors (colors), heights, widths and sizes: how beautiful it would be to announce them only once. Finally, the time has come for what we have been waiting for: write less, but do more .
')

Established practice in CSS


When people ask for declaring color variables in css (color), adding comments in the upper part of the CSS file was something like simulation of the behavior of variables:

/*-------------------------- link color: #99D1FF (light blue) box color: #555 (dark gray) --------------------------*/ 

Later, in order to update the values, I had to do a search and replace.

How it is done in LESS / Sass


The idea of ​​using variables for the style sheet was one of the reasons LESS and Sass appeared .

LESS




Sass




How it will work now


First of all, do not forget that none of the browsers support it yet. But this is how it will work in the future:
var-foo for definition, var (foo) to use.
Following the drafts:
Any property name starting with the “var-” prefix is ​​a property of a variable. (Any property name starting with the prefix “var-” is a variable property)

Example


The following rule declares the name of the property “var-header-color” for the root element and assigns the value “# 99D1FF” to it:

 :root { var-header-color: #99D1FF; } 

Further, its value can be transmitted using the variable “header-color”:

 h1 { color: var(header-color); } 

Using variable colors in gradient definitions can also be very useful. You just need to replace the value of the variables, and voila: all gradients have been updated. Sounds pretty cool to me.
Also, when creating a layout, applying variables and the calc () function can make interesting calculations.

Conclusion


CSS is not a programming language, but it should not be complicated. However, I think you will agree that using CSS variables will help avoid duplication and allow you to create more flexible style sheets.
Now that the first module of CSS variables has been released, we are looking forward to their browser support in the near future.

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


All Articles