Friday, April 04, 2008

Table-less Columnar Form or Key

I just implemented the solution to my longest outstanding CSS challenge: how to create two columns of elements with a gutter between them, without any knowledge of the height of either element. Two common examples are a graph key, and a form with labels to the left of the fields.

Your HTML could look something like this:

<dl>
    <dt>*</dt>
    <dd>required</dd>
</dl>

or this:

<div class="columnarForm">
    <label>fieldname</label>
    <div class="inputBlock">
        <input type="text" />
    </div>
</div>

The trick is to float the two elements left against each other, but make sure that the first element is set to clear left. Here’s the CSS for the form:

.columnarForm label {
    clear: left;
    float: left;
    width: 140px;
    margin: 0 10px 10px 0;
    text-align: right;
}

.columnarForm .inputBlock {
    float: left;
    margin-bottom: 10px;
}

I first attempted this challenge back in 2002 during my first days of learning hard-core CSS at Baxter. Jon asked me about it again recently, maybe last summer.

I’d be happy to see some more browser testing, might even find the time to build a sample page to facilitate that. I’ve tried it in Firefox and Safari on Mac and PC, IE6 & IE7 on PC.

No comments: