Tuesday, September 15, 2009

CSS Constants / Variables

It is very common to find repeated property values in a CSS stylesheet. CSS Variables allow authors to define variables that are reusable as property values anywhere in a stylesheet and queryable/modifiable through an extension of the CSS Object Model.

Why variables in CSS?

Many a times, any CSS developer would have felt that s/he is using repeated property values in a CSS stylesheet, for instance to make sure semantically different elements in a web page have a similar rendering and user experience. CSS does offer a way to group styles using groups of selectors, but we tend to neglect it more because of the fact that it’s difficult to maintain, decreases readability and of course semantically distinct elements rarely share all style rules.

The CSS Variables Definition

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.

Usage Example

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.

One more way of declaring variables is by prefixing the variable name with '$'

/* Company Colours */


border-bottom:1px solid $green;


oColor: #fefedb;
oBgColor: #ccc;
oMargin: 1em;
oPadding: 1em;
div#post div.entry
border: 1px solid #666;
font: normal normal normal 1em/1.6em "Lucida Grande", Lucida, Verdana, sans-serif;
margin: var(oMargin);
padding: var(oPadding);
color: var(oColor);
background-color: var(oBgColor);

Original Posts:

No comments:

Post a Comment