Thursday, July 17, 2008

CSS Body Snatching

Yes, CSS is the best way to make sure all your <p> tags use the same font but ...

Have you ever thought of using CSS to control the flow of an application?

... with Body Class Switching, CSS can dictate not only how an application appears, but also how it functions.

Let’s use the example of an application with lots of user interaction; a shopping cart.

[1] [2] [3] [4]
  1. Category selection on the left, visitor selects category ...
  2. List of matching products, visitor selects product ...
  3. Full details displayed, visitor select [Add] ...
  4. My Cart displayed.

In an AJAX application it would normally be javascript that changes the layout as the visitor moves from [1] to [4].
If, instead of making assumptions about layout, javascript simply set the class of the body tag then CSS would be able to take over control from there.

Let's try that flow again

[1] -> [2] Visitor clicks a category and Javascript sets the body class
<body class='categoryselected'>
CSS can now take over and decide to display the product thumbnails
.categoryselected #thumbnailcontainer { display:block; }

[2] -> [3] The visitor clicks on a product and javascript says:
<body class='productselected'>
CSS responds with:
.productselected #productdetailcontainer { display:block; }

[3] -> [4] The visitor clicks on ‘Add to Cart’ and javascript says:
<body class='addedtocart'>
CSS replies:
.addedtocart #cartcontainer { display:block; }

What has happened is that CSS has taken control of the visual flow application.

Why do it?

Control   If the javascript is created being someone other than the designer then the designer is in control of what are essentially design decisions.

Maintainability   If the layout of the application changes then you don't have to plough through javascript trying to find out where to mirror the changes.

Portability   The same javascript library and server side code can be used to create two apparently different applications simply because they use a different stylesheet.

User friendly   You could give your users the choice of how they want to see the application, some might want everything on the screen at the same time in a control panel kind of scenario while other might be more comfortable with basic uncluttered screens.

Philosophical   Layout is a design decision and hard coding it into javascript blurs the separation between design and functionality.

An Example

No comments: