Insights and outlooks on software development


On playing around with css

Sunday, March 15, 2009 by Thomas L

I haven't done that much of blog posting regarding web tech, but I thought I should change that, at least for once. I've become more and more intrigued by the things that can be done with css, and I thought I should share this tip on creating a comma separated list in css.

The scenario is that we have a list of things which we want to display as a comma separated list on the web. This could be in whatever language or web framework, be it Ruby on Rails, Castle MonoRail or ASP.NET MVC.

The solution is to output the list in a ul list, with all the items that should be comma separated in li elements inside the ul list, like so:

<ul class="commaseparated">
  <li>first item</li>
  <li>second item</li>
  <li>third item</li>
  <li>fourth item</li>

Then we add css rules for the commaseparated css class:

ul.commaseparated { list-style: none; margin: 0; padding: 0; }
ul.commaseparated li { display: inline; }
ul.commaseparated li:after { content: ","; } 
ul.commaseparated li:last-child:after { content: ""; }

The output is then a comma separated list. The trick here is the li:after and li:last-child:after css pseudo-classes. Read more about them at e.g. the sitepoint css reference.

One drawback is that IE 7 doesn't support css properly, so the solution with the pseudo-classes doesn't work in that browser. However, people using that browser should really look for something a bit more in the 21st century. What you could do for IE7 is using jQuery to append the commas instead of using css.

Technorati Tags: ,,

Filed under , having  

0 kommentarer: