Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align all fields as label width grows

Tags:

html

css

I have a form where the labels are on the left and the fields on the right. This layout works great when the labels have small amounts of text. I can easily set a min-width on the labels to ensure they all have the same distance to the fields. In the first picture below, this works as expected. A problem arises when the label's text becomes too long, it'll either overflow to the next line or push the field on the same line over to the left (as seen in picture 2).

This doesn't push the other labels so it is left with a "jagged" look. Ideally, it should like to style it as picture 3 with something like the following markup:

<fieldset>
    <label>Name</label><input type="text" /><br />
    <label>Username</label><input type="text" />
</fieldset>

I created a jsFiddle to show the issue.

alt text

Of course, the easy cross-browser way to solve this would be to use tables. That just creates tag-hell for something that should be so simple. Note: this does not need to support IE6.

like image 591
TheCloudlessSky Avatar asked Jan 16 '11 18:01

TheCloudlessSky


People also ask

How do I align all labels in HTML?

We specify the margin-bottom of our <div> element. Then, we set the display of the <label> element to "inline-block" and give a fixed width. After that, set the text-align property to "right", and the labels will be aligned with the inputs on the right side.

How do you align label tags?

Steps to align textbox and label Step 1: Center a div tag using margin as 0 auto . Step 2: Align the label to right and make it float to left . Step 3: Align the textbox to lef t and make it float to right . Step 4: Make both label and textbox to inline-block .


3 Answers

You're trying to create tables... without tables? Seems to me this is a situation where using tables is a perfectly fine solution. And I don't see what the 'tag-hell' should be. A tables needs a few more tags, sure, but so what? You could wrap everything in divs and simulate table cells with floats, but then you'll have a css-hell ;) .

like image 179
Alec Avatar answered Oct 12 '22 09:10

Alec


I think this is what you're looking for:

label
{
    width: 150px;
    display: inline-block;
}
input[type=text]
{
    display: inline-block;
}

http://jsfiddle.net/rQ99r/5/

like image 32
Domenic Avatar answered Oct 12 '22 09:10

Domenic


What about this solution?

<fieldset id="fs1">
    <div class="column">
        <label>Name</label>
        <label>Username text text text </label>
    </div>
    <div class="column">
        <input type="text" />
        <br />
        <input type="text" />
    </div>
</fieldset>

css:

label
{
  display: block;
}
.column{
    float:left;
}

fiddle: http://jsfiddle.net/steweb/xzHe6/

like image 22
stecb Avatar answered Oct 12 '22 11:10

stecb