Reputation: 12251
Given an html form like this:
<form action='/example/' id='example_form' method='POST' name='example_form'>
<fieldset>
<legend>Example form</legend>
<label for='age'>
Age
<input id='age' name='age' tabindex='1' type='text' />
</label>
<label for='gender'>
Gender
<select id='gender' name='gender' tabindex='2'>
<option disabled='disabled' id='gender' name='gender' value=''>Choose one:</option>
<option id='gender_female' name='gender' value='female'>Female</option>
<option id='gender_male' name='gender' value='male'>Male</option>
</select>
</label>
<label for='height'>
Height
<input id='height' name='height' size='3' tabindex='3' type='text' />
</label>
<label for='weight'>
Weight
<input id='weight' name='weight' size='4' tabindex='4' type='text' />
</label>
<input id='Save' tabindex='5' type='submit' value='Save' />
</fieldset>
</form>
How would you style it to get the classic table based layout of label to the left, field to the right, everything aligned vertically? Tables are obviously out of the question. I can't find anything on how to do this with implicit labels and just CSS.
If the answer is to not wrap the fields then so be it, but I'd prefer if a solution could be found for this as:
Any help/pointers/insight will be much appreciated.
Upvotes: 1
Views: 1432
Reputation: 4551
CSS will never cease to amaze me. Based on the answer of @magicalex I came up with the following:
label {
display: block;
position:relative;
text-align: right;
width: 100px;
margin: 0 0 5px 0;
}
label > input,
label > select,
input {
position: absolute;
left: 120px;
}
This manages to do most of what I had in mind, namely a horizontal layout with all the labels aligned to the right and all the fields aligned to the left, even if they were not the same width (which is unavoidable e.g. for iOS date pickers and the like).
However the JSFiddle illustrates the remaining problem of aligning a field if the label is broken into multiple lines (e.g. because of translations). But I guess this can be solved as well.
Upvotes: 1
Reputation: 937
Or, depending on what you mean by 'vertically aligned', you could try this.
label {
display: block;
position:relative;
margin: 0 0 5px 0;
}
label > input,
label > select {
position: absolute;
left: 70px;
width: 100px;
}
or an alternative here
Upvotes: 3
Reputation: 27405
Here are some basic stylings to get started
fieldset {width:300px;}
label {display:block;overflow:hidden;line-height:30px;}
label input, label select {float:right;}
input[type=submit] {float:right;width:100px;border:solid 1px;}
Upvotes: 3