Photography of Person Typing
How to use the new CSS variables?


 The CSS variables, technically called "non - standard CSS properties" simplify your CSS files and allow you to create interesting effects such as dynamically change the styles applied on a page and improve the features of the standard CSS properties.

Google Chrome was the only major browser that did not yet support these CSS variables. However, as of version 49, they are already available, so it is already safe to use CSS variables if your users use modern browsers (Firefox 43+, Safari 9.1+, iOS Safari 9.3+, Chrome 49+).

Why are these variables necessary?

When designing a website or web application it is common to reuse a series of colors to give consistency to the design. The problem is that repeating the same colors over and over again is not only very boring but it is very prone to making mistakes. When you want to change color, even if you do a "Find and replace" in your code editor, you will surely leave color unchanged in any file.

Of course, for a long time, many designers use preprocessors like Sass or LESS and define variables to store these values. However, these variables have a very important limitation: they cannot be modified in real-time while the page is displayed in the browser.

CSS variables do allow these changes in real-time, so it is possible, for example, to design various themes for the site so that the user can choose the style they like the most.

CSS variables in practice

CSS variables add two new functionalities to traditional CSS files:

  • They allow you to assign any value to a property whose name we can freely choose.
  • They allow reusing those values ​​in any other property thanks to the function var()

This simple example shows how to define and use a CSS variable:

: root {
   --color-principal : # 06c ;
}

#foo  h1 {
   color : var (--color-main);
}

--color-principalis a CSS property arbitrarily defined by the creator of this style sheet and whose value is #06cAlthough you can choose any name for the variables, they always have to start with two hyphens ( --).

The function var()gets the value of the property whose name is given and inserts it in the place where the function is called. In this way, the previous example is equivalent to:

#foo  h1 {
   color : # 06c ;
}

The syntax for CSS variables is a bit strange at first. The most common question is: why can't the variable just be declared as $fooinstead of --fooThe answer is that the syntax $foois reserved for the future definition of "macros", as explained in this article.

CSS variable syntax

The syntax that defines CSS variables or "non-standard CSS properties" is very simple:

- header- color : # 06c ;

Property names are case-sensitive, so --color-cabeceraand --color-Cabeceraare considered different properties. Do not think that these variables only serve to store simple values. For example, the following syntax is also valid:

--foo : if ( x > 5) this .width = 10;

Although this property would not be useful as a CSS variable, and although it cannot be used as the value of any other CSS property, this value could be processed in the browser by JavaScript to perform some complex task. This functionality opens the door to many advanced tricks and techniques that are impossible with current CSS preprocessors (Sass and LESS).

Heritage

Non-standard CSS properties also follow the same "cascading inheritance" rules as standard CSS properties, so you can define the same variable with different levels of specificity:

: root { --color : blue; }
 div { --color : green; }
 #alert { --color : red; }
* { color : var (--color); }
< p > This content looks blue (defined by ": root") </ p > 
< div > This content looks green (defined by "div") </ div > 
< div  id = "alert" >
  This content looks red (defined by "#alert")
  < p > this content also looks red
     (inherited from its parent element) </ p > 
</ div >

In this way, you can combine CSS variables with media queries in your "responsive" designs. The following example shows how to increase the margin of an item as the screen size increases:

: root {
   --separation : 4px ;
}

section {
   margin : var (--separation);
}

@ media (min-width: 600px ) {
   : root {
     --separation : 16px ;
  }
}

This example again is impossible to do with preprocessors, since variables cannot be defined within media queries.

On the other hand, the value of a variable can be defined from other variables, which is very useful to define the theme of a site:

: root {
   --color-principal : network;
  --text-logo : var (--color-main);
}

The function var()

The function var()gets the value of the indicated property. Its full syntax is as follows:

var (<property-name> [, <default-value>]?)

The first argument ( <nombre-propiedad>) is the full name of the property whose value you want to obtain. The second argument ( <valor-por-defecto>) is optional and is the value used when the property does not exist.

The default value can actually be a list of multiple values ​​separated by commas. For example, if you use var(--font-stack, "Roboto", "Helvetica");and the property --font-stackdoes not exist, the return value will be "Roboto", "Helvetica"all together.

Watch out for shortcuts in CSS properties like marginand paddingIn this case, since its values ​​are not separated by commas, the default value must not contain commas either. Example:

p {
   padding : var (--separation, 10px 15px 20px);
}

The default values ​​are very useful when designing components, as they allow you to make a "defensive design" that is prepared against the errors of others. Example:

/ * Styles defined by the component: * / 
.component  .header {
   color : var (--color-header, blue);
}
.component  .text {
   color : var (--color-text, black);
}

/ * application styles: * / 
.component {
   --color-text : # 080 ;
  / * the variable --color-header is not defined in the application,
     so the default value defined in the * / 
} component will be used

This technique is also useful for applying themes to components that use "Shadow DOM". The component designer creates an initial style with the default values ​​and then allows its customization through some CSS variables:

<! - web component definition: -> 
< x-foo >
  #shadow
    < style > p {
         background-color : var (--color-background-text, blue);
      
      }
    </ style >

    < p >
      This text has a yellow background color because the application
      so he has defined it. If not, the background would be blue.
    </ p > 
</ x-foo >
/ * in application styles: * / 
x-foo {
   --color-background-text : yellow;
}

The feature var()also has some limitations. First of all, variables cannot be used as a CSS property name. Therefore the following example is not equivalent to the style margin-top: 20px;and the browser would display an error message:

.foo {
   --side : margin-top;
  var (- side): 20px;
}

Likewise, you cannot use the value of a variable as part of the value of a property. That is why the following example is not equivalent to margin-top: 20pxand the browser would show an error message:

.foo {
   --separation : 20 ;
  margin-top : var (--separation) px ;
}

In the latter case, the solution would be to use another function called calc(), as explained in the next section.

Generating values ​​with the function calc()

The function calc()is very useful for calculating when defining the values ​​of CSS properties. All modern browsers support it without problems and it can be combined with CSS variables. Example:

.foo {
   --separation : 20 ;
  margin-top : calc (var (- separation) * 1px );
}

Using CSS variables with JavaScript

The value of CSS variables can be obtained in JavaScript using the getPropertyValue()object method CSSStyleDeclarationExample:

: root {
   --color-principal : network;
}

p {
   color : var (--color-main);
}
< p > This paragraph is red. </ p >
var stylesCss = getComputedStyle ( document .documentElement);
var value = String (stylesCss.getPropertyValue ( '--color-main' )). trim ();
// value = 'red'

Similarly, to change the value of a CSS variable in the browser itself, use the setProperty()object method CSSStyleDeclaration.

: root {
   --color-principal : network;
}

p {
   color : var (--color-main);
}
< p > This paragraph is now green. </ p >
document .documentElement.style.setProperty ( '--color-main' , 'green' );

Add the function var()in the method call to setProperty()use the value of a CSS variable as the value of another CSS variable:

: root {
   --color-principal : network;
  --secondary-color : blue;
}
< P > Now this paragraph is blue. </ p >
document .documentElement.style.setProperty (
   '- parent- color ' , 'var (- child-color)' 
);

Since CSS variables can also refer to other CSS variables from other style sheets, this real-time manipulation using JavaScript allows for very advanced dynamic behaviors.