Joshua
Joshua

Reputation: 946

How to make labels go next to input boxes in CSS

I have a form on my website in which I have aligned the input box to the right, to make the form neat and orderly.

However any time I set the form to

input[type=text]{align:right}

the labels all bunch up at the top of the form. Problem on JSfiddle..:

http://jsfiddle.net/4hX4g/

If anyone knows how to fix this annoying problem or can point me in the right direction, please do. Thank you.

Upvotes: 0

Views: 6833

Answers (2)

Mateusz Rogulski
Mateusz Rogulski

Reputation: 7455

The best way to do this is to place this fields in divs.

Here is an working example.

Upvotes: 2

David Thomas
David Thomas

Reputation: 253486

Simply define the display as inline-block, and define a width for the label:

label, input[type=text] {
    display: inline-block;
}

label {
    width: 10em;
    /* other CSS unchanged */
}

JS Fiddle demo.

The use of inline-block is to allow the elements to display inline (so next to each other on the same line), but also to allow them to have a defined with. An input is, typically, inline-block by default, so you can, similarly, get away with simply adding the following two lines to the label declaration:

label {
    display: inline-block;
    width: 10em;
    /* other CSS unchanged */
}

JS Fiddle demo.

Retaining the above CSS, you could also remove the presentational <br /> tags, and simply use CSS:

label, input {
    float: left;
}

input[type=text] + label {
    clear: left;
}

JS Fiddle demo.

Note, also, that the input element is a void/empty element; and is self-closing: <input />, not <input></input>, the final demo corrects the HTML, the first two left it uncorrected (and, honestly, unnoticed).

Upvotes: 3

Related Questions