Variables in CSS?

Definition of a variable

3.1. The @variables at-rule

CSS Variables should be defined in an @variables at-rule. An @variable at-rule is composed of the ‘@’ character followed by the ‘variables’ identifier, optional target media types (separated by commas) and a block of variable definitions. The definition of a variable must precede all style rules contained or imported in the stylesheet.

Each variable definition contained in the block of variables is a declaration composed as CSS  style declarations of an identifier, a semi-colon and one value. As in CSS declarations, optional whitespaces and comments are allowed anywhere.

3.2. Variables and @import

The definition of variables crosses @import boundaries. That means that the definition of a variable contained in a stylesheet B imported from a stylesheet A applies to all rules directly contained or imported into stylesheet A.

3.3 Calling a variable

Using the value of a variable as the value or one of the values of a property in a CSS declaration should be achieved using the new functional notation var(). This function takes only one argument being the identifier being the name of the variable. The declaration becomes invalid if the variable does not exist.Examples:

@variables {
  CorporateLogoBGColor: #fe8d12;
}

div.logoContainer {
  background-color: var(CorporateLogoBGColor);
}
@variables {
  myMargin1: 2em;
}

@variables print {
  myMargin1: 2em;
}

.data, div.entry {
  margin-left: 30px;
  margin-left: var(myMargin1);
}

In the example just above, the left margin of an element carrying the class ‘data’ will be 2em for instance for the ‘screen’ medium type, and 10px for the ‘print’ medium type in a user agent conformant to CSS Variables. A legacy non-conformant browser would apply a 30px left margin to such elements in all media types.

You may also like...