How to align input forms in HTML

I'm new to HTML and I'm trying to learn how to use forms.

The biggest issue I am having so far is aligning the forms. Here is an example of my current HTML file:

<form>
 First Name:<input type="text" name="first"><br />
 Last Name:<input type="text" name="last"><br />
 Email:<input type="text" name="email"><br />
</form>

The problem with this is, the field box after 'Email' is drastically different in terms of spacing compared to first, and last name. What is the 'proper' way to make it so that they 'line-up' essentially?

I am trying to practice good form and syntax...a lot of people might do this with CSS I am not sure, I have only learned the very basics of HTML so far.


Solution 1:

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.

Solution 2:

Another example, this uses CSS, I simply put the form in a div with the container class. And specified that input elements contained within are to be 100% of the container width and not have any elements on either side.

.container {
  width: 500px;
  clear: both;
}

.container input {
  width: 100%;
  clear: both;
}
<html>

<head>
  <title>Example form</title>
</head>

<body>
  <div class="container">
    <form>
      <label>First Name</label>
      <input type="text" name="first"><br />
      <label>Last Name</label>
      <input type="text" name="last"><br />
      <label>Email</label>
      <input type="text" name="email"><br />
    </form>
  </div>
</body>

</html>

Solution 3:

A simple solution for you if you're new to HTML, is just to use a table to line everything up.

<form>
  <table>
    <tr>
      <td align="right">First Name:</td>
      <td align="left"><input type="text" name="first" /></td>
    </tr>
    <tr>
      <td align="right">Last Name:</td>
      <td align="left"><input type="text" name="last" /></td>
    </tr>
    <tr>
      <td align="right">Email:</td>
      <td align="left"><input type="text" name="email" /></td>
    </tr>
  </table>
</form>