How to align input forms in HTML

The accepted answer (setting an explicit width in pixels) makes it hard to make changes, and breaks when your users use a different font size. Using CSS tables, on the other hand, works great:

form  { display: table;      }
p     { display: table-row;  }
label { display: table-cell; }
input { display: table-cell; }
<form>
  <p>
    <label for="a">Short label:</label>
    <input id="a" type="text">
  </p>
  <p>
    <label for="b">Very very very long label:</label>
    <input id="b" type="text">
  </p>
</form>

Here’s a JSFiddle: http://jsfiddle.net/DaS39/1/

And if you need the labels right-aligned, just add text-align: right to the labels: http://jsfiddle.net/DaS39/


EDIT: One more quick note: CSS tables also let you play with columns: for example, if you want to make the input fields take as much space as possible, you can add the following in your form

<div style="display: table-column;"></div>
<div style="display: table-column; width:100%;"></div>

you may want to add white-space: nowrap to the labels in that case.

Leave a Comment