JSS 0.2 - Nested CSS using Javascript

Why isn't CSS nested?

I guess it's not supposed to be used as a nested style system really, otherwise it would already be like that... Wouldn't it?, but I like the idea of it being nested, so now it can be!

This script parses JSON of nested CSS and returns or applies CSS to the page.

For example:

  JSS({
    '.underline': {
      'text-decoration': 'underline'
    },
    '.bold': {
      'font-weight': 'bold'
    },
    'html': {
      'body': {
        'include': '.underline, .bold',
        'background': '#fff',

        'h1': {
          'background': '#fcf',
          'include': '.non-existant'
        },

        'div#footer': {
          'include': '.underline',
          'height': '40px',

          'span#copyright': {
            'color': '#0f0',
            'background': '#f00'
          },
          'span#testing': {
            'include': '.bold',
            'color': 'black',
            'background': '#eeccff'
          }
        }
      },
      'width': '800px'
    }
  })
    

would become:


    

or by passing an option of minify: false, this:


    

When 'minify' is set to true, the script replaces 6 digit hex codes with 3 digit codes where applicable and strips out any excess whitespace and semicolons. This could be useful for preparing stylesheets using server-side javascript for smaller downloads by users. Minify is true by default.

Usage:

To use, first add jss-0.2.js (or jss-0.2-min.js) to your document, preferably in the <head/> and then add another <script/> tag linking to a .js file that contains your JSS data for example:

  JSS({
    'html': {
      'body': {
        'font-family': 'sans-serif',
        'color': '#000',

        'h1:hover': {
          'color': '#f00'
        }
      }
    }
  });
    

PHP Version

I thought it might be a bit more useful if there was a widely used server-side conversion tool for JSS, so I've converted the Javascript to a PHP5 class which currently either accepts a PHP associative array or (with a JSON decoder) a JSON string:

  <?php
  require('jss-0.2.php');

  print new JSS(array(
    'html' => array(
      'body' => array(
        'font-family' => 'sans-serif',
        'color' => '#000000',

        'h1:hover' => array(
          'color' => '#f00'
        )
      )
    )
  ));
    

or

  <?php
  require('jss-0.2.php');
  require('JSON.php');

  print new JSS('{
    "html": {
      "body": {
        "font-family": "sans-serif",
        "color": "#000",

        "h1:hover": {
          "color": "#f00"
        }
      }
    }
  }', array(
    // a static class method
    'jsonDecoder' => array('JSON', 'decode')
    // or a standard function
    // 'jsonDecoder' => 'json_decode'
  ));
    

I might work on other server-side language parsers too...

Changelog