Saturday, December 14, 2013

Using CSS Variables

Using CSS Variables

I'm very excited to say that as of Firefox 29, CSS variables are a reality.

For years web developers have been plauged with the unfortunate realization of not being able to store colors/sizes/images/etc in their code for re-use. Instead, the best one could do is create a ton of classes to store whatever shared properties you had. E.G.
    
    <style>
      .sharedBackground {
        background-color: red;
      }
    </style>

    <body>
      <div class="sharedBackground" id="boxA"> Hello </div>
      <div class="sharedBackground" id="boxB"> World </div>
      etc..
    </body>
Which is fine, except for when you want to share a bunch of different attributes. Then this happens:
<div class="sharedBackground sharedColor sharedFont etc" id="boxA"> Hello World </div>
That's pretty ugly.

Good news is though, CSS variables are coming (eventually to all platforms), but you can try them out now in the current Firefox Nightly!

Usage:

As usage goes, it's pretty simple. Variables are declared like: --something. You then use these variables with the syntax: var(--something); And these variables inherit from their parents, so a simple example of CSS variables would be:
    <style>
      .main {
        --mainBackground: red;
      }
      #boxA {
        background-color: var(--mainBackground);
      } 
      #boxB {
        background-color: var(--mainBackground);
      } 
    </style>

    <body class="main">
      <div id="boxA"> Hello </div>
      <div id="boxB"> World </div>
      etc..
    </body>
It's as easy as that!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.