HTML form with side by side input fields
For the sake of bandwidth saving, we shouldn't include <div>
for each of <label>
and <input>
pair
This solution may serve you better and may increase readability
<div class="form">
<label for="product_name">Name</label>
<input id="product_name" name="product[name]" size="30" type="text" value="4">
<label for="product_stock">Stock</label>
<input id="product_stock" name="product[stock]" size="30" type="text" value="-1">
<label for="price_amount">Amount</label>
<input id="price_amount" name="price[amount]" size="30" type="text" value="6.0">
</div>
The css for above form would be
.form > label
{
float: left;
clear: right;
}
.form > input
{
float: right;
}
I believe the output would be as following:
The default display style for a div is "block." This means that each new div will be under the prior one.
You can:
Override the flow style by using float as @Sarfraz suggests.
or
Change your html to use something other than divs for elements you want on the same line. I suggest that you just leave out the divs for the "last_name" field
<form action="/users" method="post"><div style="margin:0;padding:0">
<div>
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
... rest is same
Put style="float:left"
on each of your divs:
<div style="float:left;">...........
Example:
<div style="float:left;">
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>
<div style="float:left;">
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
To put an element on new line, put this div below it:
<div style="clear:both;"> </div>
Of course, you can also create classes in the CSS file:
.left{
float:left;
}
.clear{
clear:both;
}
And then your html should look like this:
<div class="left">
<label for="username">First Name</label>
<input id="user_first_name" name="user[first_name]" size="30" type="text" />
</div>
<div class="left">
<label for="name">Last Name</label>
<input id="user_last_name" name="user[last_name]" size="30" type="text" />
</div>
To put an element on new line, put this div below it:
<div class="clear"> </div>
More Info:
- CSS Float Clear Tutorial