Skip to content Skip to sidebar Skip to footer

CSS For Aligning TextBox And Label

I'm trying to take my Form layout away from tables and entering the world of div's and css. I'm having difficulty though in my layout. I'd like to order the elements where a label

Solution 1:

nest the input elements in the labels so the text label and field are grouped.

this usage is specified in the HTML4 spec:

To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.

<div id="content">
    <label>
        Request Id<br />
        <input id="txt_RequestId" type="text" />
    </label>

    <label>
        District<br />
        <input id="txt_District" type="text" />
    </label>
</div>

CSS:

#content
{
    position: absolute;
    top: 110px;
    left: 350px;
    width: 775px;
    height: 605px;
}

#content label
{
    display:inline;
    float:left;
    margin-right:4px;
    vertical-align:top;
}

example

Then apply display:inline and float:left to the <label>s (or use display:inline-block instead if you don't have to worry about older browsers example)


Solution 2:

Change this

#content input
{
    float:left;
    margin:1px 20px 1px 1px;
}

to this

#content input
{
    display:inline;
    margin:1px 20px 1px 1px;
}

That is remove the float:left and replace with display:inline;.

Example: http://jsfiddle.net/jasongennaro/ptKEh/

EDIT

@mdmullinax pointed out that the question also requested the text be above the input field

Missed that ;-)

In that case, remove the display rules and use three brs

<div id="content">
    <label for="txt_RequestId">Request Id</label><br />
        <input id="txt_RequestId" type="text" />

    <br />

    <label for="txt_District">District</label><br />
        <input id="txt_District" type="text" />
</div>

Revised example: http://jsfiddle.net/jasongennaro/ptKEh/2/


Solution 3:

I generally use tables for forms that are laid out like this. They are much easier to work with than CSS (IMO) and the structure is much more clear.

<table>
    <tr>
        <td>
            <label for="txt_RequestId">Request Id</label>
            <br /><input id="txt_RequestId" type="text" />
        </td>
        <td>
            <label for="txt_District">District</label>
            <br /><input id="txt_District" type="text" />
        </td>
    </tr>
</table>

CSS is very good for moving elements around with respect to their container. However when you want things to be positioned in a very regular way, dependent on other elements, it can really obfuscate the logic. <table>s are much more explicit about this.


Post a Comment for "CSS For Aligning TextBox And Label"