Two-column lists when order doesn’t matter

I’m working on a site that uses an extended navigation menu grouped into sub-sections. Each section, in turn, groups its links into two columns of roughly equal height.

In CSS and HTML, this can be a pain. You can break the columns yourself, of course, but you have to maintain that every time there’s a change.

Or, if the order of the links doesn’t particularly matter, you can just float alternating elements to the left and right. Kind of like this:

ul {
  width:300px;
  border: 1px solid black;
  overflow: auto;
}
li {
  width: 145px;
  border-top: 1px solid blue;
}
li:nth-child(odd) {
  float:left;
  clear: left;
}
li:nth-child(even) {
  float: right;
  clear: right;
}

This works great, except for one thing: nth-child CSS selectors don’t work in older browsers (specifically, IE8 and earlier). If this is an issue, we can add a couple lines of jQuery to add ‘odd’ and ‘even’ classes. The only thing to watch out for is that in jQuery, the ‘:odd’ selector is zero-based, while the CSS ‘odd’ is one-based:

$('li:odd').addClass('even'); 
$('li:even').addClass('odd');

Sadly, IE8 not only won’t recognize the :nth-child selector, it will completely ignore the entire line of CSS if it sees that unknown pseudoclass. We’ll need to add a whole new selector to accommodate it:

li.odd {
  float:left;
  clear: left;
}
li.even {
  float: right;
  clear: right;
}

jsFiddle

We can use Modernizr to run this code only when the user’s browser fails to support CSS3 selectors, but for two lines of jQuery code, it’s probably not worth the trouble.

Now the only browsers left out in the cold are IE8 and earlier who also have JavaScript turned off. Personally, I can live with that.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*