CSS: Right Aligned Form

Author: MikeW    Date: 2016-06-05 18:48   

This page describes the steps needed to create right aligned text for an HTML form. A sample page that uses this technique follows.

RightAlignedForm.html (Click to See Output)

Here is the CSS rules and HTML for this example. A description of some of the key features follows.

RightAlignedForm.html (Click for Source)

   3:  <title>Right Aligned Form Labels</title>
   4:  <link href="/css/blip.css" rel="stylesheet" type="text/css"></link>
   6:  <style type="text/css">
   7:  #centeredBox{ border:1pt solid black; margin:10px auto 10px auto; width:400px; padding:10px;}
   8:  .formHeader{font-size:24pt; margin:10px; text-align:center;}
   9:  .formItem{clear:both;}
  10:  form label{float:left; text-align:right; width:150px;}
  11:  #main { width:440px; }
  13:  </style>
  16:  <div id="main">
  17:  <h3>Right Aligned Form Labels</h3>
  18:  <p>This page demonstrates how to create a form that has its labels right aligned with text fields.</p>
  19:  <div id="centeredBox">
  20:    <div class="formHeader">Address Form</div>
  21:    <form id="addressForm" method="post">
  22:      <div class="formItem">
  23:        <label>First Name:</label>
  24:        <input type="text" name="firstName" size="25" maxlength="30"></input>
  25:      </div>
  26:      <div class="formItem">
  27:        <label>Last Name:</label>
  28:        <input type="text" name="lastName" size="25" maxlength="30"></input>
  29:      </div>
  30:      <div class="formItem">
  31:        <label>Address:</label>
  32:        <input type="text" name="streetAddress" size="25" maxlength="30"></input>
  33:      </div>
  34:      <div class="formItem">
  35:        <label>City:</label>
  36:        <input type="text" name="city" size="25" maxlength="30"></input>
  37:      </div>
  38:      <div class="formItem">
  39:        <label>State:</label>
  40:        <input type="text" name="state" size="25" maxlength="30"></input>
  41:      </div>
  42:      <div class="formItem">
  43:        <label>Zip:</label>
  44:        <input type="text" name="zip" size="25" maxlength="30"></input>
  45:      </div>
  46:    </form>
  47:  </div>
  48:  </div>

The Outer Box

Line 7 defines the rule for #centeredBox. This creates the box surrounding the form. A border is defined. The box is centered by setting the left and right margins to auto. A little padding is added for good measure. A width is set keep the white space around the form elements reasonable.

Form Elements

The key rules on are line 9 and 10. Line 10 makes the text float. A width is set to 150 pixels and the text is then right-aligned. This makes all our form labels line up with the text boxes.

Line 9 merely resets the float. Since each form element is in a formItem div tag, this has the effect of inserting a line break without using a <br> tag.