1

Why is it so awkward to get a two-column form layout to work in CSS?

All I want to accomplish is:

Name:         Joe Dude
Age:          30
Description:  Some long text here that needs to wrap if it exceeds the border,
              but still indent to align w/ the first line.
Location:     New York

Here is my HTML (w/ some embedded Razor):

<div class="section">
    <label>Name:</label>
    <span>@person.Name</span>
    <label>Age:</label>
    <span>@person.Age</span>
    <label>Description:</label>
    <span>@person.Description</span>
    <label>Location:</label>
    <span>@person.Location</span>
</div>

Here is my CSS:

.section
{
    padding: 5px;
    border-radius: 7px;
    border: 1px solid #aaa;
    margin:0 auto;
}
.section label
{
    display:block;
    font-weight:bold;
    text-align:right;
    width:50%;
    float:left;
}

.section span
{
    display:block;
    text-align:left;
    width:50%;
    float:right;
}

This almost works, except the border is collapsed upwards, and some other weird wrapping is going on below the form.

What am I missing?

Thanks in advance.

3 Answers 3

2

overflow:hidden; on .section

The floats essentially make the .section "empty" because they float out of it. The overflow hack fixes this.

You could also remove the float: from one of the elements inside.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! The overflow: hidden part seems backwards to me. But it certainly fixes my issue.
this does not seem to solve the problem entirely, labels and spans swap places at small widths (or wide content)
Actually, overflow: auto; suffices, IIRC.
1

I started out with @graup's solution, and altered it as it wasn't working w/ wrapped text.

Here is the CSS I ultimately went with:

.section
{
    width:800px;
    overflow: hidden;
}
.section label
{
    display:block;
    width:400px;
    float:left;
}

.section span
{
    width:400px;
    display: inline-block;
}

Comments

0

Alternative solution:

.section label {
    display: block;
    float: left;
    width: 200px;
}
.section span {
    display: block;
    margin-left: 200px;
}
.section span:after {
    content: "";
    display: block;
    clear: left;
}

this relies on static width for left column, but should also wrap nicely with percentages!

I'm not sure if IE7 and older likes the :after selector.

Demo: http://jsfiddle.net/y4NcC/

More information, and support for legacy IE: http://colinaarts.com/articles/float-containment/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.