Search code examples
htmlcssformsalignmentmargin

Alignment of form fields


I am trying to create a form to create a new user for my website. I would like to have the form fields horizontally aligned, to make it look nicer. I have tried doing this using some simple CSS, but I cannot get it to work*.

<html>
    <form name="newUserForm" method="post" action="createUserScript.php">
        <p>Username:           <input name="username" type="text" autofocus class="formField"> </p>  
        <p>E-mail:             <input name="email" type="text" class="formField">              </p>
        <p>Password:           <input name="password" type="text" class="formField">           </p>
        <p>Repeat password:    <input name="passwordRepeat" type="text" class="formField">     </p>
        <p>Administrator:      <input type="checkbox" name="isAdmin" class="formField">        </p>
    </form>
</html>

And the CSS for the .formField class is

.formField {
    margin-left: 150px;
    width: 200px;
}

The whole thing is located in a <div> with the following properties (I dont know if this has anything to say)

#content {
    padding: 10px;
    margin-left: 250px;
    font-family: arial;
}

Currently it seems to be making the margin from where the text ends, but I am not sure. What am I missing here?

*I could probably find some crazy workaround to make it work, but I cannot think of anything that seems reasonable.


Solution

  • This is what I'd do (using labels):

    <html>
        <style type="text/css">
            label{display:block; float:left; width:130px;}
            .formFeild{width:200px;}
            p{clear:both; margin-bottom:5px;}
        </style>
    
        <form name="newUserForm" method="post" action="createUserScript.php">
            <p><label>Username:</label><input name="username" type="text" autofocus class="formField"> </p>  
            <p><label>E-mail:</label><input name="email" type="text" class="formField">              </p>
            <p><label>Password:</label><input name="password" type="text" class="formField">           </p>
            <p><label>Repeat password:</label><input name="passwordRepeat" type="text" class="formField">     </p>
            <p><label>Administrator:</label><input type="checkbox" name="isAdmin" class="formField">        </p>
        </form>
    </html>