two-column form labels and inputs

The usual technique to maintain a two-column form (labels on the left, inputs on the right) is to put the input after the label, fix the width of both elements, and float them to the left. This works well, but I prefer to keep inputs inside of label elements when possible, just to cut down on the number of attributes. (If the input is outside of its label, the input needs an id= attribute and the label needs a matching for= attribute.)

One solution would be to put the text inside the label inside a span, but that’s still adding extra HTML. This solution works by fixing the width of the label and then absolutely-positioning the input element outside of it to the right.

label {
  position: relative;
  display: block;
  overflow: visible; /* if necessary */
  box-sizing: border-box; /* if necessary */
  width: 9em;
  padding-right: 1em;
  margin-bottom: 0.5em;
}
label select,
label input {
  position: absolute;
  top: 0;
  left: 100%;
  width: 300px;
}
/* add overriding styles for radio and checkbox inputs

jsFiddle example

Leave a Reply

Your email address will not be published. Required fields are marked *

*