If you have a list of items which are just too long to display vertically or tabular data that you want to convert with css, you can divide them in columns.
How? By using negative margins without using any floats or relative positioning.
Here’s an example:
Col1
Access Key
1
2
3
4
5
6
Col2
Resulting action
Skip Navigation
Home
Laboratory
Tutorials
Templates
Accessibility
The result is to get col1 and col2 next to each other, nicely lined up.
You could use tables to display the list but it’s also possible with just Css, but without floats or relative positioning. The advantage is that you don’t run into float bugs or/and having to use hacks for IE6.
Let’s start first with the HTML:
<ul class="test">
<li class="col1 title">Access Key</li>
<li class="col1">1<li>
<li class="col1">2<li>
<li class="col1">3<li>
<li class="col1">4<li>
<li class="col1">5<li>
<li class="col1">6<li>
<li class="col2 top">Resulting action<li>
<li class="col2">Skip Navigation<li>
<li class="col2">Home<li>
<li class="col2">Laboratory<li>
<li class="col2">Tutorials<li>
<li class="col2">Templates<li>
<li class="col2">Accessibility<li>
</ul>
The Css goes as follows:
I assume you already have reset the paddings and margins on your lists.
.test li {
line-height:1.5;
}
.col1{
margin-left: 1em;
}
.col2 {
margin-left:7em;
}
.top {
margin-top:-11.5em;
margin-bottom: 1em;
}
.title {
margin-bottom: 1em;
}
Let’s go over it step by step:
Step 1: setting line-height
Setting a line-height on the li is needed because we’ll use that to calculate the height of the column in step 3.
.test {
line-height:1.5;
}
Step 2: Indenting col1 (depending on the layout) and making room for the second column
I guess this doesn’t need much explanation.
.col1{
margin-left: 1em;
}
.col2 {
margin-left:7em;
}
Step 3: pulling the second column in place and creating some space.
We pull the second column in place so everything lines up perfectly.
We do this by using negative margins.
.top {
margin-top:-11.5em;
margin-bottom: 1em;
}
The value for the negative top margin is calculated as follows:
The number of items x line-height = height of col2.
This should gives us a negative value of 10.5em. (7 x 1.5)
But you’ll notice that in our example it’s 11.5em.
The reason for that is because of the vertical space i wanted to create between the first li of each col and the other li’s.
Depending on your lay-out you may or not need it.
So, because .top has a bottom margin of 1em, you need to increase the negative margin by the same amount: 10.5em becomes 11.5em.
Setting the same vertical space between each li for col1 is also done with a bottom margin of 1em:
.title {
margin-bottom: 1em;
}
Checked in Opera, IE6,IE7,IE8, FF,Safari and Chrome.
End result
Have fun