Thursday, February 23, 2012

Slim Up Your HTML with CSS3 - Zebras


Last time, I explored one way that new CSS3 properties slim up our markup by eliminating wrapping elements. But those wrapping elements aren't the only things clouding up our HTML! Another common way that it gets cluttered is with extra class names. And today, I'm exploring a way that CSS3 helps us eliminate those, too!

Now, if you know me at all, you know that I absolutely love drinking tea. In fact, at home I've got a trunk of tea that currently has no fewer than 24 different kinds of tea. And that's not counting the bags of loose leaf tea in the cupboard. So, yeah... I like tea.

Anyway, here's a list of some of my favorite kinds.  I applied classic CSS2 zebra striping to it so that you can more obviously tell when a single item in the list spans more than one line.




Zebra striping... check! But what's up with the class name that was added to the first and third list items? Earl Grey and Darjeeling are both marked with a class of "odd". Notwithstanding the irony that Earl Grey is highlighted in... um... grey, there's nothing inherently odd about either of these teas. (And odds are, you'd find me drinking one. And to find me drinking one would not be odd...)

So the designation "odd" has nothing to do with the tea and everything to do with its position in the list. So, it's not semantic. Helpful for our styling, but not semantic.

To help keep our markup lean and clean, CSS3 comes to the rescue with nth-child. Let's look at the CSS3 way of striping our zebra:


Nice! The nth-child argument above says to use every second (2n) item in the list. I added the -1 in order to apply the style rule to the odd items instead of the even items.

And just look at that markup! We were able to accomplish the same styling without tacking on any superfluous class names.

And sure, it looks good in the simple example above, but it gets even better in real life! -- In a web app, you'd include programming logic to determine whether you're on an even or odd record. So CSS3 isn't just removing the class names for us. It's removing some presentation code, too!

Well, we've shed quite a few HTML pounds between the borders and the zebras. But it doesn't stop there! Stay tuned for more ways that CSS3 will keep your markup lean and clean.

No comments:

Post a Comment

Profile Picture
Dave Leeds
My Hobbies:
  • Programming
  • Cartooning
  • Music Writing
Full Profile