Multi-Columns

Recently (yesterday), on A List Apart appeared two articles on multi-column layouts for the web and how you can achieve them. I’ve found particularly interesting the one about lists, but I would like to suggest another way of doing this.

Their final solution involves giving a distinct class to each list item. What a clutter in the HTML! What if the style sheet didn’t need all these class attributes? Let’s find out.

First you need to know about the adjacent selector. If you write li + li as a CSS selector, it means any list item following a list item. This means the corresponding style rules will apply to every list item, except the first one in a list. Nice! Now, let’s apply this.

I’ll base myself on the example 6 file given in the ALA article to explain the rest. So maybe you will want to take a look.

The first use of list item’s classes in the style sheet sets a negative margin on the sixth and eleventh items so they start on a new column. We will replace the class names with adjacent selectors. So this:

li.feve,
li.kava
{
    margin-top: -6em;
}

Now becomes this:

ol li+li+li+li+li + li, 
ol li+li+li+li+li + li+li+li+li+li + li
{
    margin-top: -6em;
}
ol li+li+li+li+li + li+li, 
ol li+li+li+li+li + li+li+li+li+li + li+li
{
    margin-top: 0em;
}

The first rule sets a negative margin-top to any item preceded by five or ten other items. The second rule will “reset” top margin to zero for other items in the list (those preceded by six or eleven other items). The result is that only the sixth and eleventh items have a negative top margin.

Note on spacing: I’ve grouped adjacent list items by five — the number of element per column — to make it easier to read for me and for my readers.

Then we need to handle horizontal positioning. It work the same way, except this time it involves much less hassle than making the rules than using classes on every item. So we replace this mess:

ol li.aloe,
ol li.berg,
ol li.cale,
ol li.dami,
ol li.elde
{
    margin-left: 0em;
}
ol li.feve,
ol li.ging,
ol li.hops,
ol li.iris,
ol li.juni
{
    margin-left: 10em;
}
ol li.kava,
ol li.lave,
ol li.marj,
ol li.nutm,
ol li.oreg,
ol li.penn
{
    margin-left: 20em;
}

By these three elegant rules:

ol li, 
{
    margin-left: 0em;
}
ol li+li+li+li+li + li
{
    margin-left: 10em;
}
ol li+li+li+li+li + li+li+li+li+li + li
{
    margin-left: 20em;
}

The result is now exactly the same as in example 6, except that you can now remove the class attributes in the HTML and reorder/insert/delete items at will without bothering about the style sheet.

We can truly say we have separated style from the content.

The only drawback seems to be that the adjacent selector doesn’t work on Windows IE. :-(


Comments

natalie

That’s really great! I’m so glad there are guys like you to do the thinking ahead of me. ;)


  • © 2003–2024 Michel Fortin.