Blog
20/04/2017

CSS Custom Properties or Variables

It’s now a reality. We can finally use Custom Properties or CSS Custom Properties!

But first, let’s start with a solid <h2>, followed by a brief <p> summary.

CSS Custom Properties

Or, how to work magic in your CSS stylesheet.

CSS Custom Properties introduce a “new” concept in CSS: the use of variables natively within your CSS—and even from JavaScript.

Why “new” in quotes? You’re probably familiar with CSS preprocessors. They’ve been all the rage, but with the arrival of Custom Properties and as browser support grows, preprocessors are on their way out. At the end of this article, you’ll find a browser support table, but spoiler: around 70% of users already have a browser that supports Custom Properties.

 

CSS and Custom Properties

To see the difference, let’s compare a standard CSS stylesheet without Custom Properties to the same stylesheet rewritten using Custom Properties.

Suppose we want a body with a specific background color, which we’ll later use for text color in a layer, and we’ll also use the body’s text color as the background color for that layer.

Layer 1 will have 20px padding—the same value as the margin-top for layer 2.


body{
     background-color:#1b1b1b;
     color:#fff;
}
.capa1{
     padding:20px;
     color:#1b1b1b;
     background-color:#fff;
}
.capa2{
     margin-top:20px;
}

Now, let’s recreate the same example, but this time using Custom Properties.


:root{
     --color1:#1b1b1b;
     --color2:#fff;
     --mainSpacing:20px;
}
body{
     background-color:var(--color1);
     color:var(--color2);
}
.capa1{
     padding:var(--mainSpacing);
     color:var(--color1);
     background-color:var(--color2);
}
.capa2{
     margin-top:var(--mainSpacing);
}

With :root, we declare variables that are accessible throughout the entire CSS document. Use a double dash — to define a variable and its value. Then, to use the variable, simply call var(–VARIABLE);.

Now imagine the benefits in a stylesheet with over 1,000 lines of code. If you need to update a value, you only have to change it in one place, and it updates everywhere.

 

Taking it further

Or even two steps further. CSS Custom Properties let you perform calculations, use conditional logic, and set default values if a variable isn’t defined. Sounds like JavaScript, right? But you can do all this directly in your CSS.

You can add, multiply, compare values, and apply different values based on conditions.


.caja{
     /*If variable1 isn’t set, 10px will be used*/
     margin-top:var(--variable1, 10px);

     /*You can also use another variable as a fallback*/
     padding-top:var(--variable1,var(--variable2));

    /*You can add, subtract, multiply, and divide (*note the spacing for addition and subtraction)*/
     padding-top:calc(var(--variable1) + 10px);
     height:calc(var(--variable1) - 5px);
     line-height:calc(var(--variable1) * 2);
     width:calc((var(--variable1) - 5px)/2);
     
}

More examples:


:root{
     /*You can create text to be inserted later with :before*/
     --text:"Click to view";
}
.caja:before{
     content:var(--text);
}
.caja2:before{
     /*You can append more text after your variable (e.g., a project link)*/
     content:var(--text)' our full project';
}
.caja2:before{
     /*Or use it for a news link*/
     content:var(--text)' our news';
}

Conditional example:


:root{
     /*Accessible via JavaScript*/
     --variableCond: if(x > 5) this.width = 10;
}

 

Browser support

As you can see, virtually all browsers support Custom Properties… Except Explorer! What a surprise, I DIDN’T SEE THAT COMING! It’s a reminder of those glorious years when we had to jump through hoops to make things work in Explorer 6.

Fortunately, unlike back then, now less than 4% of users are on Explorer. Not a big deal.

Currently, 70.9% of users have browsers that support Custom Properties. That’s a huge number.

propiedades personalizadas o custom properties

http://caniuse.com/#feat=css-variables

Did you like it?
Related articles
Ready to start
your project?

We assess your current situation and outline the next steps.

Contact now
Our site uses cookies to collect information about your device and browsing activity. We use this data to improve the site, ensure security and deliver personalized content. You can manage your cookie preferences by clicking here.
Accept cookies Configure Decline cookies
Basic cookie information
This website uses cookies and/or similar technologies that store and retrieve information when you browse. In general, these technologies can serve very different purposes, such as, for example, recognizing you as a user, obtaining information about your browsing habits or personalizing the way in which the content is displayed. The specific uses we make of these technologies are described below. By default, all cookies are disabled, except for technical ones, which are necessary for the website to function. If you wish to obtain more information or exercise your data protection rights, you can consult our Política de cookies".
Accept cookies Configure
Technical cookies needed Always active
Technical cookies are strictly necessary for our website to work and for you to navigate through it. These types of cookies are those that, for example, allow us to identify you, give you access to certain restricted parts of the page if necessary, or remember different options or services already selected by you, such as your privacy preferences. Therefore, they are activated by default, your authorization is not necessary.rnThrough the configuration of your browser, you can block or alert the presence of this type of cookies, although such blocking will affect the proper functioning of the different functionalities of our website.
Cookies de análisis
Las cookies de análisis son las utilizadas para llevar a cabo el análisis anónimo del comportamiento de los usuarios de la web y que permiten medir la actividad del usuario y elaborar perfiles de navegación con el fin objetivo de mejorar los sitios web.
Confirm preferences
contact us
Form

Tell us
your project

Indicate the general context of your organization and the planned scope of the project.
Code Barcelona, ​​as responsible for the processing of your data, will process it in order to respond to the query and/or request that you make to us through this contact form. Privacy Policy.
Title
Popupcontent
Analysis of your digital situation

We will review your current digital situation. We will get in touch to understand your context and jointly assess which areas to analyze, after which we will prepare an audit including key findings and recommendations.

Code Barcelona, ​​as responsible for the processing of your data, will process it in order to respond to the query and/or request that you make to us through this contact form. Privacy Policy.
Aceptar