Using float for Form Layout

First published on 2007-02-27, updated on 2008-07-02.

The HTML specification defines a lot of stuff for forms. It’s hard to know what to use, especially if you do CSS layout.

Here’s what I do for commercial websites.

Simple Login

You see these everywhere, looking something like this:

Login Demo

Markup for Login

<form action="?" method="post">
 <fieldset class="text">
  <legend>Login Demo</legend>
  <div class="textbox">
   <label for="name">Name:</label> <input id="name" name="name" type="text" size="20">
  </div>
  <div class="textbox">
   <label for="password">Password:</label> <input id="password" name="password" type="text" size="20">
  </div>
  <div class="checkbox">
   <input id="remember" name="remember" type="checkbox" value="1"> <label for="remember">Remember me</label>
  </div>
  <div class="button">
   <input type="submit" name="remember" value="Log In">
  </div>
 </fieldset>
</form>

Styles for Login

I applied class="text" onto the <fieldset> since it mostly contains text boxes. This allows the CSS to use .text .checkbox to make the checkbox align with the text boxes:

/* Form Controls */
form {
 margin: 0 0 1em 0;
}
div.textbox {
 clear: left;
 margin: 0 0 0.5em 0;
}
.textbox label {
 float: left;
 width: 20%;
 text-align: right;
}
.textbox input {
 width: 75%;
 margin-left: 2%;
}
.text .checkbox input {
 margin-left: 22%;
 padding: 0;
}
.button {
 text-align: right;
}
.text .button {
 width: 98%;
}
.text .button input {
 margin-right: 2px; /* Textbox borders */
}

Aligning controls can be done without using <table> for layout or chains of &nbsp;.