Search code examples
htmlcssformsalignment

Moving form elements into a position where they look stacked


I have a login form I'm creating... The problem is, I can't align the text boxes and text correctly.

It looks like this at the moment:

Align fail

But i need it to look like:

Correctly aligned, Text is all different sizes but text and textboxes are stacked up and not further to the left

This is very hard to explain. What I really want is for the text and text boxes to stay on the same X axis but the Y axis can be changed.

I think it requires a table, however I do not know how to use those. If it does require one, an explanation of how to use a table to align these forms would be great.

Thank you for your help.


Solution

  • Use text-align with float/display: inline-block. Inputs are inside labels. Example.

    <label>
        <span>username:</span>
        <input>
    </label>
    
    <label>
        <span>password:</span>
        <input>
    </label>
    
    <label>
        <span>country:</span>
        <select>
            <option>option
        </select>
    </label>
    
    <style>
        label {display: block; overflow: hidden; margin: 5px 0 0; height: 24px; line-height: 24px;}
        label > * {float: left;}
        label span {width: 90px; text-align: right; margin-right: 5px;}
        label span + * {width: 100px; height: 20px; line-height: 20px; padding: 0;}
    </style>
    

    http://jsfiddle.net/tb34rv1x/

    Or the second (of many) option. Inputs are outside labels:

    <label for="a">username</label>
    <input id=a>
    
    <label for="b">password:</label>
    <input id=b>
    
    <label for="c">country:</label>
    <select id="c">
        <option>option
    </select>
    
    <style>
        label {float: left; clear: left; width: 100px; text-align: right; margin-right: 10px;}
        label + * {float: left;}
        * {margin-top: 5px;}
    </style>
    

    http://jsfiddle.net/tb34rv1x/1/