开发者

Two column layout in CSS without using tables

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:

.sec开发者_StackOverflowtion
{
    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.


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.


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;
}


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜