Thursday, February 26, 2009

Exploring Alternative CSS Formats

I've been thinking about the syntax of CSS. I don't like it. I find it doesn't parse easilly. Could an existing data format be better?

CSS
body{
  color: #3300dd;
  background: #331000 url(http://auctiva.com/images/logo.gif) no-repeat top left;
  font-family: Arial, sans-serif;
}
h1,h2,h3{
  color: #aaf0cc;
  font-family: Tahoma, sans-serif;
  font-style: normal;
  font-weight: normal;
}
#rightSidebarPanel, #leftSidebarPanel{
  background-color: #ffffff;
}

Regular CSS is nice and compact but there's a lot of redundancy and some of the code requires too much memory. Sure you can combine all the background properties into one but there's little rules you have to remember that make it harder.

JSON
[
    {
      "s":["body"],
      "p":{
        "background":{
          "color": "#33A222",
          "image": "http://auctiva.com/images/logo.gif",
          "repeat": "no-repeat",
          "position": "top left",
        },
        "font":{
          "family":'Arial, sans-serif',
        },
        "color":"#000000"
      }
    },{
      "s":["h1","h2","h3"],
      "p":{
        "color":"#a0ff00",
        "font":{
          "family":"Tahoma,sans-serif",
          "weight":"normal",
          "style":"normal"
        }
      }
    },{
      "s":["#rightSidebarPanel","#leftSidebarPanel"],
      "p":{
        "background":{
          "color":"#ffffff" 
        }
      }
    }
  ];

JSON is nice cause it can quickly be turned into JavaScript. The standardized structure means there's less special cases and the syntax is more learnable. There's an awful lot of text that's not data though, maybe something else would be better.

YAML
- s:body
  p: 
    background:
      color: #331000
      image: http://auctiva.com/images/logo.gif
      repeat: no-repeat
      position: top left
    font: 
      family: Arial, sans-serif
- s: [h1,h2,h3]
  p: 
    color: #aaf0cc
    font:
      family: Tahoma, sans-serif
      style: normal
      weight: normal
- s: [#rightSidebarPanel, #leftSidebarPanel]
  p: 
    background: 
      color: #ffffff

Yaml is my favorite so far it's easy to read and can be parsed cleanly. I don't like the s & p keys but I don't think I can make the key the selector as selectors can be arrays. Still, I think this format can really work well.

2 comments:

Andy Watts said...

http://haml.hamptoncatlin.com/docs/rdoc

SASS has gained some traction within the rails community.
I believe it makes coding CSS more object oriented.

Jethro Larson said...

Yeah. I've looked at SASS. It's really cool. My current CSS style was heavily influenced by it's structure. Sadly I don't work in Rails so there's little chance for me to enjoy it.